如何调用用c ++编写的程序调用我用c编写的DLL

时间:2014-03-12 11:10:23

标签: c++ c visual-studio-2012 dll dev-c++

我在C中开发了一个dll,并且用这个方法调用了我的C ++程序

#include <cstdlib>
#include <iostream>
#include <windows.h>

#ifdef __cplusplus
extern "C" {
#endif
#include "mydll.h"
#ifdef __cplusplus
}
#endif
using namespace std;

int main(int argc, char *argv[])
{
    struct myown_struct *ss = NULL;
    int i = 0,j = 0, result = 0;
    struct myown_struct2 *s = NULL;
    myfunction("string1", "string2", "string3", 1500);
    system("PAUSE");
    return EXIT_SUCCESS;
}

mydll.h:

#ifndef _DLL_H_
#define _DLL_H_

#if BUILDING_DLL
# define DLLIMPORT __declspec (dllexport)
#else /* Not BUILDING_DLL */
# define DLLIMPORT __declspec (dllimport)
#endif /* Not BUILDING_DLL */

struct myown_struct {
  int fd;
  char buf[32];
  unsigned int len;
} __attribute__((packed));

DLLIMPORT void myfunction(char *s1, char* s2, char *s3, int n);

#endif /* _DLL_H_ */

我收到此错误:

C:\ Users \ user01 \ Desktop \ test \ main.cpp在函数int main(int, char**)中  C:\ Users \ user01 \ Desktop \ test \ main.cpp myfunction' undeclared (first use this function)

我该如何解决?

2 个答案:

答案 0 :(得分:2)

您的标头文件mydll.h似乎缺少myfunction的声明。纠正遗漏和你的代码将编译。

最重要的是,您需要确保:

  • 编译DLL时创建的.lib导入库在链接C ++程序时传递给链接器。
  • 当您尝试运行程序时,可以找到DLL。最好通过将DLL放在与可执行文件相同的目录中来实现。

我还要评论我希望在头文件中看到extern "C",而不是强迫头文件的每个用户都写extern "C"。头文件确实应该是独立的。

答案 1 :(得分:1)

由于您使用的是VC ++,因此您可以将现有的API用于相同的

typedef void (*myfunction)(char *buf1, char *buf2,char *buf3,char *buf4);
HMODULE hModule = LoadLibrary(_T("mydll.dll"));
if(hModule!=NULL)
    myfunction GetMyFunction = (myfunction) GetProcAddress(hModule,"myfunction");

现在使用GetMyFunction()

希望这会有所帮助