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

标签 c# go dll cgo

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

最佳答案

它适用于 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 在这里不起作用。

关于c# - 在 C# 中从 Go 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55913015/

相关文章:

c# - 使用 Microsoft.AspNetCore.NodeServices 调用 JS 文件时获取 Node 调用超时错误

goroutines 的执行顺序

go - postgresql golang 创建表错误,pq : syntax error at or near "$1"

ASP.NET MVC 入口点

c# - Visual Studio 2015 SSIS - 未在 SSIS 工具箱中选取自定义 SSIS 组件

c# - 计算通过所有点的曲线

c - C 中的 OpenMP 在 Windows 中使用 GCC 创建 DLL

c# - 无法将 Visual Studio 制作的 C++ DLL 导入 Windows 上的 Visual Studio C# 项目

c# - IBM Watson 对话服务错误 : cannot convert from 'method group' to 'conversation.onMessage'

http - 一个 HTTP 定界符来统治它们