在C#中从Go调用函数

user10400458:

我正在尝试从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)))
}

这是我的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
user10400458:

它与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);
    }
}

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章