从c ++ dll返回double *到delphi程序

时间:2013-10-23 01:22:06

标签: c++ delphi pointers dll dllexport

我试图将double(声明为double *)的数组返回给delphi程序。在c ++ dll项目中我有

#define DllExport   __declspec( dllexport )
extern double* array;
extern "C"
{
    DllExport double* SomeMethod(double);
}
卸载Dll时

array被删除

BOOL APIENTRY DllMain( HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
    )
{

switch( ul_reason_for_call ) 
{ 
...

    case DLL_PROCESS_DETACH:
        delete [] array;
        break;
}
    return TRUE;  // Successful DLL_PROCESS_ATTACH.
}

当我在c ++控制台应用程序中测试我的dll时,我在使用来自dll的SomeMethod后得到了正确的结果。接下来我试着在Delphi中测试我的dll但是方法返回的数组内容是错误的。我使用了以下代码。

TSomeMethod = function(level : Double): PDouble; cdecl;
...
var
    SomeMethod: TSomeMethod;
    arr: PDouble;
...
    if Assigned(SomeMethod) then
        begin
          arr:= SomeMethod(15);
          writeln(arr^:2:0);
          inc(arr);
          writeln(arr^:2:0);
        end
...

从c ++ dll返回double*以在delphi中使用的正确方法是什么?

P.S。其他方法以正确的方式工作。例如,dll返回char*,在delphi中我使用PAnsiChar

获取它

更新

这是来自文件的一些C ++代码,其中写有SomeMethod

double* array; // yea it's an array that declared as external in other file;
...
double* SomeMethod(double level)
{
    ...
    deque<double> arrayToReturn;
    ... // some actions with deque
    array= new double[arrayToReturn.size()];
    for (unsigned int i = 0; i<arrayToReturn.size(); i++)
        array[i] = arrayToReturn[i];
    return array;
 }

1 个答案:

答案 0 :(得分:1)

您问题中的代码运行正常。这意味着问题出在其他地方。这是证据:

<强> C ++

#include <Windows.h>

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
    )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

extern "C" {

__declspec(dllexport) double* SomeMethod(double)
{
    double* array = new double[2];
    array[0] = 42;
    array[1] = 666;
    return array;
}

}

<强>的Delphi

{$APPTYPE CONSOLE}

uses
  Windows, SysUtils;

type
  TSomeMethod = function(level : Double): PDouble; cdecl;

var
  SomeMethod: TSomeMethod;
  arr: PDouble;
  lib: HMODULE;

begin
  lib := LoadLibrary('MyDll.dll');
  Win32Check(lib<>0);
  SomeMethod := GetProcAddress(lib, 'SomeMethod');
  Win32Check(Assigned(SomeMethod));
  arr:= SomeMethod(15);
  Writeln(arr^:3:0);
  inc(arr);
  Writeln(arr^:3:0);
  Readln;
end.

<强>输出

 42
666