我正在尝试从 Golang 制作一个 .dll 文件以在 C# 脚本中使用。但是,我无法使一个简单的示例起作用。
这是我的 Go 代码:
package main
import (
"C"
"fmt"
)
func main() {}
//export Test
func Test(str *C.char) {
fmt.Println("Hello from within Go")
fmt.Println(fmt.Sprintf("A message from Go: %s", C.GoString(str)))
}
Run Code Online (Sandbox Code Playgroud)
这是我的 C# 代码:
using System;
using System.Runtime.InteropServices;
namespace test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello");
GoFunctions.Test("world");
Console.WriteLine("Goodbye.");
}
}
static class GoFunctions
{
[DllImport(@<path to test.dll>, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern void Test(string str);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在构建 dll:
go build -buildmode=c-shared -o test.dll <path to go file>
Run Code Online (Sandbox Code Playgroud)
输出是
Hello
Hello from within Go
A message from Go: w
panic: runtime error: growslice: cap out of range
Run Code Online (Sandbox Code Playgroud)
小智 5
它使用byte[]而不是使用string,即使用以下 C# 代码:
using System;
using System.Runtime.InteropServices;
namespace test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello");
GoFunctions.Test(System.Text.Encoding.UTF8.GetBytes("world"));
Console.WriteLine("Goodbye.");
}
}
static class GoFunctions
{
[DllImport(@<path to test.dll>, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern void Test(byte[] str);
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定为什么string在这里不起作用。