External dll function with .h file gives no return value, but gives an error. (DLL and function does work perfect in VBA)

huangapple go评论55阅读模式
英文:

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 &quot;C&quot; {
  __declspec(dllimport) int __stdcall WieOpenDev(void);
}

Code in main.cpp:

int (*fcnPtrGetDev)();
fcnPtrGetDev = WieOpenDev;
std::cout &lt;&lt; fcnPtrGetDev &lt;&lt; &#39;\n&#39;;

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 &lt;&lt; fcnPtrGetDev;

see godbolt demo.

Note: To actually call the function pointed to by the function pointer, you need to use

std::cout &lt;&lt; fcnPtrGetDev();

instead of

std::cout &lt;&lt; fcnPtrGetDev;

The latter results in the pointer value being printed instead of the result of calling the function.

huangapple
  • 本文由 发表于 2023年6月2日 02:29:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定