3

Hello Go Lang and C# gurus,

Good day. I would like to ask if anyone of you have tried calling a C# DLL functions (Class Library type) from a Go program?

I have made some initial research and saw these articles:

- https://github.com/golang/go/wiki/WindowsDLLs
- https://stackoverflow.com/questions/27849137/golang-call-windows-dll-functions

But these are DLLs created out from C Win32 implementations. I tried searching for C# DLL loaded into Go program all of them will tell you that you need to have a C++/C (Win32) wrapper before you can call it on a Go program.

Plus, the links above will tell you that Go is expecting a "C" declaration I think (which is of type __declspec) or the likes (e.g. WINAPI).

Is there a way in this case where we can completely skip the C/C++ wrapper and directly call the C# DLL functions in Go?

Your enlightening ideas and inputs will be greatly appreciated =)!

Thanks

Artanis Zeratul
  • 963
  • 2
  • 14
  • 40
  • 2
    https://github.com/matiasinsaurralde/go-dotnet – Gusman Jun 09 '17 at 00:26
  • Are you trying to make objects available or just specific static functions? What are the access patterns for the code? How frequent does it need to happen? Could you consider using .NET instead of Go? Could you wrap the C# code into an EXE and just use it that way (you could use std in/out potentially, or other communication to use the C# code). – WiredPrairie Jun 09 '17 at 00:58
  • 1
    hello @WiredPrairie, thanks a lot for your inputs. To answer your question, I am considering to access objects but if not probably just plain functions. But I think, since its C#, it should be objects. I am not sure with exposing it through EXE yet. I cannot have it in pure C# only, because it is a transition/porting project. Thanks a lot once again =)! – Artanis Zeratul Jun 09 '17 at 01:24
  • 1
    You'll incur a significant amount of overhead to do this, both in complexity of implementation and build, but also at run time. I'd suggest sticking with one language if possible if you want this type of integration. – WiredPrairie Jun 09 '17 at 10:33
  • C# code is not machine code; it's managed code meant to be interpreted by the CLR (the .NET VM). There is no good way to directly interface with managed CLR bytecode from a non-CLR executable. – Adrian Jun 09 '17 at 13:52

1 Answers1

4

Option 1 Turn your .NET DLL into a COM component like this, then you can invoke it from golang following the steps in your first link. Remember this option is for windows only.

Option 2 Wrap the DLL within a simple C# console application, and invoke the application in golang using os/exec. Your final program is still cross-platform if your C# DLL is cross-platform.

Both options need a basic knowledge of C#, either creating COM components, or writing a console application to invoke the DLL. IMO the latter is easier.

Cheng Chen
  • 42,509
  • 16
  • 113
  • 174