Golang DLL与Delphi之间如何传递数组

Golang DLL与Delphi之间如何传递数组 我尝试用Go语言编写一个简单的DLL,返回一个整数数组。

//export Test
func Test() uintptr {
names := []int{12345, 678910, 1314155}
	return uintptr(unsafe.Pointer((*C.int)(unsafe.Pointer(&names[0]))))
}

我尝试在Delphi中获取这个数组,但是失败了:

function TTest.Test(): boolean;
type
  TIntArray =  Array of integer;
var
  TestFunc: TTestFunc;
  p: PInteger;
  OutputData: TIntArray;
begin
  Result := False;
  if DLLHandle <> 0 then
  begin
    TestFunc := GetProcAddress(DLLHandle, 'Test');
    if Assigned(TestFunc) then
    begin
      p:= TestFunc();
      OutputData:= TIntArray(p);
      OutputDebugString(PChar(IntToStr(OutputData[0])));
    end;
  end;
end;

有什么建议吗?

致礼


更多关于Golang DLL与Delphi之间如何传递数组的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang DLL与Delphi之间如何传递数组的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang DLL与Delphi之间传递数组时,主要问题是内存管理和数组结构的不匹配。Go的切片包含长度和容量信息,而Delphi期望的是纯数据数组。以下是正确的实现方式:

Go DLL代码:

package main

import "C"
import "unsafe"

//export Test
func Test() uintptr {
    names := []int32{12345, 678910, 1314155}
    return uintptr(unsafe.Pointer(&names[0]))
}

//export TestWithLength
func TestWithLength() (uintptr, int) {
    names := []int32{12345, 678910, 1314155}
    return uintptr(unsafe.Pointer(&names[0])), len(names)
}

func main() {}

Delphi调用代码:

function TTest.Test(): boolean;
type
  TIntArray = array[0..2] of Integer;
var
  TestFunc: function: UIntPtr; stdcall;
  TestFuncWithLength: function(out length: Integer): UIntPtr; stdcall;
  p: ^TIntArray;
  i: Integer;
  length: Integer;
begin
  Result := False;
  if DLLHandle <> 0 then
  begin
    // 方法1:固定长度数组
    TestFunc := GetProcAddress(DLLHandle, 'Test');
    if Assigned(TestFunc) then
    begin
      p := Pointer(TestFunc());
      for i := 0 to 2 do
        OutputDebugString(PChar(IntToStr(p^[i])));
    end;

    // 方法2:动态获取长度
    TestFuncWithLength := GetProcAddress(DLLHandle, 'TestWithLength');
    if Assigned(TestFuncWithLength) then
    begin
      p := Pointer(TestFuncWithLength(length));
      for i := 0 to length - 1 do
        OutputDebugString(PChar(IntToStr(p^[i])));
    end;
  end;
end;

关键要点:

  1. 使用int32确保Go和Delphi的整数类型匹配(4字节)
  2. 直接返回数组首元素的指针,而不是切片结构
  3. 通过单独的返回值传递数组长度
  4. 在Delphi中使用固定长度数组或动态分配内存

编译Go DLL:

go build -buildmode=c-shared -o test.dll

这样就能正确在Go DLL和Delphi之间传递数组数据了。

回到顶部