C ++ DLL导入:函数调用返回错误的结果

c++ dllimport: function call returns wrong result

本文关键字:返回 错误 结果 函数调用 DLL 导入      更新时间:2023-10-16

我正在尝试公开c ++项目中的一些方法,以便从另一个项目中调用它们。

在我的 DLL 项目中,我公开了这些方法:

class IFilter
{
public:
virtual double Filter(double n) = 0;
};
__declspec(dllexport) IFilter* ButterworthCreate(int order, double cutoffFrequency, double sampleRate)
{
return new VButterworth(order, cutoffFrequency, sampleRate);
}
__declspec(dllexport) double ButterworthFilter(IFilter* handle, double n)
{
double nResult = -1;
if (handle){
nResult = handle->Filter(n);
}
return nResult; 
}

在我的控制台应用程序中,我尝试像这样使用它们:

typedef long(*ButterworthCreate)(int, double, double);
typedef long(*ButterworthFilter)(int, double);

int _tmain(int argc, _TCHAR* argv[])
{
std::string s = "D:\WORK\FilterConsole\Debug\Butterworth.dll";
std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();
HINSTANCE hGetProcIDDLL = LoadLibrary(sw);
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
// resolve function address here
ButterworthCreate create = (ButterworthCreate)GetProcAddress(hGetProcIDDLL, "ButterworthCreate");
ButterworthFilter filter = (ButterworthFilter)GetProcAddress(hGetProcIDDLL, "ButterworthFilter");
if (!create || !filter) {
std::cout << "could not locate the function" << std::endl;
return EXIT_FAILURE;
}
int handle = create(1, 1, 1);
double result = filter(handle, 10);
return 0;
}

可以解析函数并创建返回有效指针,但过滤器函数的结果为负数。

过滤器函数的实现只是

double CButterworth::Filter(double n)
{
return n * n;
}

调试时,我可以看到结果在 dll 中计算正确,但控制台应用程序中的结果很奇怪。

谁能解释一下我错过了什么?谢谢

你有

__declspec(dllexport) double ButterworthFilter(IFilter* handle, double n)

typedef long(*ButterworthFilter)(int, double);

这两者是不平等的。特别是在指针为 64 位的 64 位系统上,而指针仍然是 32 位int。另请注意,使用 MSVC 时,即使在 64 位系统上,long也是32 位。

如果你想创建一个与C兼容的接口,我建议你改用不透明的数据类型。并禁用使用extern "C"的名称重整。