DLL文件中函数的预期行为在C中编写并从CPP文件打电话

  • 本文关键字:文件 CPP 打电话 函数 DLL c++ c
  • 更新时间 :
  • 英文 :


我已经在C中写了一个DLL文件并从CPP打电话,但我没有得到预期的行为,请向我解释它的工作原理
我的dll文件(.c and .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

被解雇的,非匹配的预处理指令在编译时间对编译器的编译器"不可见",就像您从代码中手动将其删除一样,如果

,它们不做运行时的工作时间

最新更新