英文:
External dll function with .h file gives no return value, but gives an error. (DLL and function does work perfect in VBA)
问题
外部 DLL 函数返回整数(无参数),会导致编译错误:
> 无法将 'int*' 转换为 'int (*)()' 进行赋值
我期望一个 int
返回值(在 VBA 中可以工作,但在 C++ 中不行)。
在 .h
文件中:
extern "C" {
__declspec(dllimport) int __stdcall WieOpenDev(void);
}
在 main.cpp
中的代码:
int (*fcnPtrGetDev)();
fcnPtrGetDev = WieOpenDev;
std::cout << fcnPtrGetDev << '\n';
在编译时会报错:
> 无法将 'int*' 转换为 'int (*)()' 进行赋值
我尝试在 VBA 中使用这个 DLL 函数。它可以完美工作,返回值是 6
,这是正确的。
但是在 C++ 中会出现上述错误。
我还尝试过:
int GetDev;
GetDev = WieOpenDev;
在编译时会产生不同的错误:
> 无效从 'int (*)()' 转换为 'int' [-fpermissive]
英文:
External DLL function which returns an integer (no arguments) gives a compiler error:
> cannot convert 'int*' to 'int (*)()' in assignment
I expect an int
return value (in VBA it does work, but in C++ it does not).
In .h
file:
extern "C" {
__declspec(dllimport) int __stdcall WieOpenDev(void);
}
Code in main.cpp
:
int (*fcnPtrGetDev)();
fcnPtrGetDev = WieOpenDev;
std::cout << fcnPtrGetDev << '\n';
Gives an error while compiling:
> cannot convert 'int*' to 'int (*)()' in assignment
I tried to use this DLL function in VBA. It does work perfectly, the return value is 6
, which is correct.
But C++ gives that error.
I also tried:
int GetDev;
GetDev = WieOpenDev;
Which gives a different error while compiling:
> invalid conversion from 'int (*)()' to 'int' [-fpermissive]
答案1
得分: 1
代码应该适用于x64
目标,但对于Win32
目标,__stdcall
实际上会产生影响。对于这两个目标,以下代码应该可以编译:
int (__stdcall* fcnPtrGetDev)();
fcnPtrGetDev = WieOpenDev;
std::cout << fcnPtrGetDev;
请查看godbolt演示。
注意:要实际调用函数指针指向的函数,您需要使用
std::cout << fcnPtrGetDev();
而不是
std::cout << fcnPtrGetDev;
后者将打印指针值,而不是调用函数的结果。
英文:
The code should work fine for x64
targets, but for Win32
targets the __stdcall
actually makes a difference here. For both targets the following code should compile:
int (__stdcall* fcnPtrGetDev)();
fcnPtrGetDev = WieOpenDev;
std::cout << fcnPtrGetDev;
see godbolt demo.
Note: To actually call the function pointed to by the function pointer, you need to use
std::cout << fcnPtrGetDev();
instead of
std::cout << fcnPtrGetDev;
The latter results in the pointer value being printed instead of the result of calling the function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论