今天同事遇到一个问题:error C2564:‘xxxx’:a function-style conversion to a built-in type can only take one argument
之前没有遇到过,于是到网上查了一下,发现如下文章的error场景与他的十分类似:
http://forums.codeguru.com/showthread.php?327586-C-Newbie-What-have-I-done-wrong
文章中提到的原因是:
typedef 定义的函数指针,是一种类型。我们调用方法要使用该类型的变量。
下面是我的测试:
dll:
头文件:其中DLLEXPORT是定义在stdafx.h中 #define DLLEXPORT
#ifdef DLLEXPORT
#define MY_API _declspec(dllexport)
#else
#define MY_API _declspec(dllimport)
#endif
extern "C" {
MY_API int send(char* thisNumber, int flag);
}
源文件
#include "stdafx.h"
#include "ErrorTestDll.h"
#include <iostream>
int send(char* thisNumber, int flag) {
printf("hello world! number:%c, flag:%d \n", *thisNumber, flag);
return 1;
}
调用dll的控制台工程代码:
#include "stdafx.h"
#include <Windows.h>
typedef int (*mySend)(char* thisNumber, int flag);
int _tmain(int argc, _TCHAR* argv[])
{
HINSTANCE dllHandle = NULL;
dllHandle = LoadLibrary("E:\\test\\ErrorTestDll\\Debug\\ErrorTestDll.dll");
mySend fp = (mySend)GetProcAddress(dllHandle, "send");
mySend fp2;
char ch = 'A';
//int t = fp(&ch, 1); // 正确的调用形式
//int t = fp2(&ch, 1);
int t = mySend(&ch, 1); // 文中出错是由于这样的调用。
printf("t : %d", t);
while(1);
return 0;
}
编译结果:
error C2564: 'mySend' : a function-style conversion to a built-in type can only take one argument
如测试结果所示:使用函数指针的定义直接当作函数来调用,确实是不行的。
其实导致错误的原因很简单,就是没有正确使用函数指针。
另外,上述测试代码中使用dll的方式,也值得我们参考:
1、它是动态加载dll的,
2、它没有依赖dll的头文件,仅仅是通过GetProcAddress指定的函数名定位到函数的。
3、typedef定义的函数指针,让我们知道dll的本质,我只要知道你的接口(dll)是什么样子的,我就可以调用你。
调用dll的过程非常简洁,我们可以应用到自己的项目中。