exportgo.go
/*
GoLang DLL example. Goals: load golang dll into fpc/lazarus, and load golang
dll into another go executable.
The syntax
//export SomeFunc
needs to be used above the function you want to export
To compile this program run:
go build -buildmode=c-archive exportgo.go
then compile goDLL.c that exports the functions for GCC to link, and run:
gcc -shared -pthread -o goDLL.dll goDLL.c exportgo.a -lWinMM -lntdll -lWS2_32
*/
package main
import "C"
import "fmt"
//export GetIntFromDLL
func GetIntFromDLL() int32 {
return 42
}
//export PrintHello
func PrintHello(name string) {
fmt.Printf("From DLL: Hello, %s!\n", name)
}
//export PrintBye
func PrintBye() {
fmt.Println("From DLL: Bye!")
}
func main() {
// Need a main function to make CGO compile package as C shared library
}
go build -buildmode=c-shared -o exportgo.dll exportgo.go 编译成dll
下面是delphi 调用代码
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
windows,
System.SysUtils;
var h: THandle;
type
TProc = procedure(); cdecl;
var
PrintBye: TProc;
const
GO_LIB = 'goDLL.dll';
PROC1 = 'PrintBye';
function LoadLib: boolean;
var p: pointer;
begin
h := LoadLibrary(GO_LIB);
writeln('handle: ', h);
p := GetProcAddress(h, PROC1);
if p = nil then begin
writeln('error getting procedure address: ', PROC1);
result := false;
end;
PrintBye := TProc(p);
end;
procedure UnloadLib;
begin
closehandle(h);
end;
var
c: char;
begin
writeln('Loading library: ', GO_LIB);
if LoadLib then begin
PrintBye();
end;
writeln('Press enter to exit');
readln;
writeln('Unloading library: ', GO_LIB);
UnloadLib;
try
{ TODO -oUser -cConsole Main : Insert code here }
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.