Use another language to call a function: Difference between revisions
Content deleted Content added
m whitespace |
Go solution |
||
Line 104: | Line 104: | ||
} |
} |
||
}</lang> |
}</lang> |
||
=={{header|Go}}== |
|||
Possible—if you allow a small stretch of the task specification. |
|||
Cgo, Go's interface to C, allows calls from C to Go, but only if it gets to start Go first. That is, it doesn't work with a program started with C startup code and C main(), but only with a program started with Go startup code and Go main(). |
|||
Thus, I changed the specified C code to begin as follows, |
|||
<lang c>#include <stdio.h> |
|||
#include "_cgo_export.h" |
|||
void Run() |
|||
{ |
|||
char Buffer [1024]; |
|||
size_t Size = sizeof (Buffer); |
|||
if (0 == Query (Buffer, &Size)) |
|||
...</lang> |
|||
The biggest change is that I renamed main, since it is no longer a C main function. Another small change is that the extern declaration is replaced by an include. The included file is generated by cgo and contains an equivalent extern declaration. And then one more small change, I changed the type of the variable Size from unsigned to size_t. This is to satisfy Go's type matching which is more strict than C's. |
|||
In the Go code, below, you see that all main does is call C.Run. The C code is then in the driver's seat. |
|||
<lang go>package main |
|||
// #include <stdlib.h> |
|||
// extern void Run(); |
|||
import "C" |
|||
import "unsafe" |
|||
func main() { |
|||
C.Run() |
|||
} |
|||
const msg = "Here am I" |
|||
//export Query |
|||
func Query(cbuf *C.char, csiz *C.size_t) C.int { |
|||
if int(*csiz) <= len(msg) { |
|||
return 0 |
|||
} |
|||
pbuf := uintptr(unsafe.Pointer(cbuf)) |
|||
for i := 0; i < len(msg); i++ { |
|||
*((*byte)(unsafe.Pointer(pbuf))) = msg[i] |
|||
pbuf++ |
|||
} |
|||
*((*byte)(unsafe.Pointer(pbuf))) = 0 |
|||
*csiz = C.size_t(len(msg) + 1) |
|||
return 1 |
|||
}</lang> |
|||
Output: |
|||
<pre> |
|||
Here am I |
|||
</pre> |
|||
=={{header|HaXe}}== |
=={{header|HaXe}}== |