dqsxsmi3704
dqsxsmi3704
2019-04-30 02:04

在C#中从Go调用函数

已采纳

I'm trying to make a .dll file from Golang to be used in a C# script. However, I can't make a simple example work.

Here is my Go code:

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)))
}

Here is my C# code:

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

I'm building the dll from:

go build -buildmode=c-shared -o test.dll <path to go file>

The output is

Hello
Hello from within Go
A message from Go: w

panic: runtime error: growslice: cap out of range
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douqiangchuai7674 douqiangchuai7674 2年前

    It works with byte[] instead of string, that is, with the following C# code:

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

    I'm not sure why string does not work here though.

    点赞 评论 复制链接分享

为你推荐