gpt4 book ai didi

c++ - 用 c 编写并从 cpp 文件调用的 dll 文件中函数的预期行为

转载 作者:行者123 更新时间:2023-11-28 04:47:17 24 4
gpt4 key购买 nike

我用 c 编写了一个 dll 文件并从 cpp 调用它,但我没有得到预期的行为,请解释一下它是如何工作的
我的 dll 文件(.c 和 .h)

#include <stdio.h>
#if defined (WIN32)
#if defined(FUNCTIONS_STATIC)
#define FUNCTIONS_API
#else
#if defined(FUNCTIONS_EXPORTS)
#define FUNCTIONS_API __declspec(dllexport)
#else
#define FUNCTIONS_API __declspec(dllimport)
#endif
#endif
#else
#define FUNCTIONS_API
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef MYMATHDLL_EXPORTS
#define MYMATHDLL_API __declspec(dllexport)
#else
#define MYMATHDLL_API __declspec(dllimport)
#endif
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <math.h>

#define PI 3.1415
MYMATHDLL_API double PowerOf3(double UserNumber);
#ifdef __cplusplus
}
#endif

.c

#ifdef __cplusplus
double PowerOf3(double UserNumber)
{
return UserNumber * UserNumber;
}
#endif
#ifndef __cplusplus
double PowerOf3(double UserNumber)
{
return UserNumber ;
}

#endif

我将上面的函数编译为dll并在cpp文件中使用它

.cpp 文件

#include <iostream>
#include <fstream>
#include <cmath>
#include <windows.h>
#include <stdio.h>
#include <fstream>
#include "modell.h"
#include "modellfunktionen.h"
#ifdef __cplusplus
extern "C"
{
#include "MyMathDll.h"
}
#endif
using namespace std;
typedef double(*MYFUN2)( double op);
int main(int argc, char** argv) {
widepath ="C:\\Personal\\VB_practice\\MyMathDll\\x64\\Debug\\MyMathDll.dll";
hMod = LoadLibraryA(widepath);
//cout << widepath << endl;
MYFUN2 pfun2 = (MYFUN2)GetProcAddress(hMod, "PowerOf3");
cout << pfun2(10) << endl;
}

给我结果 10,但我预计它是 100,因为 cplusplus 已定义。我哪里弄错了。

最佳答案

它不起作用,因为这些定义在编译时被检查,你将它编译为 C 代码,所以编译器检测到你没有使用 C++,所以

#ifndef cplusplus

触发的、不匹配的预处理器指令在编译时对于编译器是“不可见的”,就像您从代码中手动删除它们一样,它们不会像运行时那样工作,如果

关于c++ - 用 c 编写并从 cpp 文件调用的 dll 文件中函数的预期行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49029956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com