Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute Go function in C#

Tags:

c#

go

Is there any way to execute a Go function from C#? For Python I would use Ironpython for example.

I know that I could spawn a process to execute a Go script, but I don't really want to fallback to such a solution, if possible.

A Google search didn't reveal anything, so is there any way to do that using an API? Or do I have to fallback on processes?

like image 806
Rakete1111 Avatar asked Jun 10 '16 19:06

Rakete1111


People also ask

Does Go use C?

Go does not require any C libraries if that's what you're asking.

How do you create a Go function?

In the Go language, we declare a function by typing the func keyword. After typing in the func keyword, we have to write the name of our function. Following that, we list the parameters (if any are present), and then list the return type of the function being defined.

How do functions work in Go?

A function in Go is also a type. If two function accepts the same parameters and returns the same values, then these two functions are of the same type. For example, add and substract which individually takes two integers of type int and return an integer of type int are of the same type.

What is import C Go?

The import "C" line allows us to interface with C code through our go program. The comments above it is actual C code that can be consumed by the rest of the code. We include stdlib. h so that we can call malloc and free; and greeter. h for our greeter function.


2 Answers

I think Frank's answer is not right! Golang supports many build mode, and one is c-shared mode, it means you can use it like a c module. e.g: https://www.trs.ai/c%E8%B0%83%E7%94%A8golang%E4%BB%A3%E7%A0%81/

like image 152
nathan.xu Avatar answered Oct 12 '22 22:10

nathan.xu


EDIT: my answer is now not true, since Go has been updated since I posted. this stackoverflow thread will help you solve your problem.

ORIGINAL ANSWER:

I don't think you're going to have much luck finding what you're looking for. Go is statically linked and C# doesn't support that.

From C#, calling a pre-compiled executable and reading the output is the easiest thing I can think of.

like image 44
Frank Bryce Avatar answered Oct 13 '22 00:10

Frank Bryce