【问题标题】:Calling function from Go in C#在 C# 中从 Go 调用函数
【发布时间】: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

标签: c# go dll cgo


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    相关资源
    最近更新 更多