-1

I am trying to use a Golang library that is compiled as a shared C library in my .NET application. It's compiled with the following command: go build --buildmode=c-shared -o main.dll

My Golang code looks like this:

func DoRequest(request *C.char) *C.char {

    // ...
    // b = []byte
    return (*C.char)(unsafe.Pointer(&b[0]))
}

How can I get this string back into a usable form in the .NET world? I've tried this but I get a panic from Go:

    [DllImport("C:\\Users\\GolandProjects\\awesomeProject\\main.dll", EntryPoint = "DoRequest", CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.LPStr)]
    extern static string DoRequest(byte[] requestJsonString);

    static void Main(string[] args)
    {
        var result = DoRequest(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new Request
        {
            // ...
        })));
        Console.ReadLine();
    }
Sam
  • 602
  • 9
  • 21
  • 1
    `Encoding.UTF8.GetBytes` is not the way to go in any case -- this spits out bytes, not a null-terminated string. Use `UnmanagedType.LPUTF8Str` to marshal UTF-8 encoded strings. (I don't know enough about Go to tell if this suffices to make the P/Invoke work.) – Jeroen Mostert Aug 20 '21 at 16:56
  • Please don't be lazy and search the SO. A simple search yields, say, [this](https://stackoverflow.com/a/48227520/720999). – kostix Aug 20 '21 at 19:12

1 Answers1

0

Please start with thoroughly reading the doc on cgo.

Strings in Go are not NUL-terminated, so there's thre ways to gateway a Go string across a C-compatible shared library barrier:

  • Copy it to a C-style NUL-terminated string—yielding a pointer to the first character of a copy, and passing it.

  • Pass the pointer to the 1st character of a Go string, and then also explicitly pass the string length along with it.

  • Teach "the other side" about the native Go's string representation and use it. A string in Go is a (packed) struct containing a pointer and a pointer-sized integer.

kostix
  • 51,517
  • 14
  • 93
  • 176