首页 > 解决方案 > 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 中的结果计算正确,但我的控制台应用程序中的结果很奇怪。

谁能解释我错过了什么?非常感谢

标签: c++

解决方案


你有

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

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

这两者不相等。特别是在 64 位系统上,指针是 64 位,而int仍然是 32 位。另请注意,使用 MSVClong也是32 位,即使在 64 位系统上也是如此。

如果你想创建一个 C 兼容的接口,我建议你改用opaque 数据类型。并禁用名称修改使用extern "C"


推荐阅读