c# - 在 C# 中从 Go 调用函数
问题描述
我正在尝试从 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
在这里不起作用。
推荐阅读
- python - 如何对单词搜索的结果进行编码以计算单词的出现次数
- python - 如何将函数从 view.py 传递到 html
- r - 根据值 r 查找行号
- c++ - 这是维护大型 C++ 项目的良好目录结构吗?
- agent-based-modeling - Repast Java:如何在没有 GUI 的情况下直接在 Eclipse 中运行模型以及如何在没有 Eclipse 的情况下以无头模式运行它
- amazon-web-services - 将mysql数据库转换为dynamodb模型
- javascript - 参数结果隐式具有任何类型
- python - 如何组合长度不等的数据帧
- microservices - 微服务的事务管理
- python - 多次调用类中的方法,变量保持一致