c++ - c++ dllimport:函数调用返回错误结果
问题描述
我正在尝试在 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 位,而int
仍然是 32 位。另请注意,使用 MSVClong
时也是32 位,即使在 64 位系统上也是如此。
如果你想创建一个 C 兼容的接口,我建议你改用opaque 数据类型。并禁用名称修改使用extern "C"
。
推荐阅读
- r - 使用因子向量选择 data.frame 行
- asp.net-mvc - 如何在 ASP.NET MVC 框架中通过 TempData 将参数传递到另一个页面?
- java - 异常不能转换为 Throwable
- python - 当我更新记录时,在 Django 中抛出了一个结束行
- r - 用 Rmarkdown 编织一个 word 文档。在 for 循环中在 2 个字幕之间插入绘图会产生问题
- javascript - Javascript:我可以在随机端口打开 websocket 服务器连接吗
- android - 组件总是接口实现吗?
- statsmodels - stasmodels SARIMAX 预测
- python - 获取字符串的所有未分组部分
- c - 添加函数有问题