-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();
    }
2
  • 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.) Commented Aug 20, 2021 at 16:56
  • Please don't be lazy and search the SO. A simple search yields, say, this. Commented Aug 20, 2021 at 19:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.