C# 在C中从Go调用函数#

C# 在C中从Go调用函数#,c#,go,dll,cgo,C#,Go,Dll,Cgo,我正在尝试从Golang生成一个.dll文件,用于C#脚本。然而,我不能让一个简单的例子起作用 这是我的密码: 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

我正在尝试从Golang生成一个.dll文件,用于C#脚本。然而,我不能让一个简单的例子起作用

这是我的密码:

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#代码:


它使用
byte[]
而不是
string
,即使用以下C代码:

使用系统;
使用System.Runtime.InteropServices;
名称空间测试
{
班级计划
{
静态void Main(字符串[]参数)
{
Console.WriteLine(“你好”);
测试(System.Text.Encoding.UTF8.GetBytes(“世界”);
Console.WriteLine(“再见”);
}
}
静态类函数
{
[dlliport(@,CharSet=CharSet.Unicode,CallingConvention=CallingConvention.StdCall)]
公共静态外部无效测试(字节[]str);
}
}

我不确定为什么
string
在这里不起作用。

在不完全知道Go的情况下,看起来至少在字符串中断之前获得了它的第一个字符。这可能是因为您正在以
*C.char
而不是一个简单的
字符串进行打字?
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);
    }
}
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
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);
    }
}