【发布时间】:2019-09-18 15:33:04
【问题描述】:
我正在尝试从 Golang 制作一个用于 C# 脚本的 .dll 文件。但是,我无法制作一个简单的示例。
这是我的 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)))
}
这是我的 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);
}
}
我正在从以下位置构建 dll:
go build -buildmode=c-shared -o test.dll <path to go file>
输出是
Hello
Hello from within Go
A message from Go: w
panic: runtime error: growslice: cap out of range
【问题讨论】:
-
在不完全了解 Go 的情况下,看起来您至少在字符串中断之前获得了字符串的第一个字符。可能是因为您将类型转换为
*C.char而不是简单的string?