Call a foreign-language function: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 2,796:
 
There is no way to use the <code>str</code> family of types, yet do manual memory management; FFI manages automatically. Code that wants to manually manage a foreign resource referenced by pointer should use <code>cptr</code> or <code>carray</code>, depending on required semantics.
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="vlang">
#include "stdlib.h"
#include "string.h"
 
// Declare C functions that will be used.
fn C.strdup(str &char) &char
fn C.strcat(dest &char, src &char) &char
 
fn main() {
txt_1 := "Hello World!"
txt_2 := " Let's Wish for Peace!"
// Memory-unsafe operations must be marked as such (unsafe {...}), or won't compile.
unsafe {
dup := C.strdup(txt_1.str)
println('${cstring_to_vstring(dup)}')
addto := C.strcat(dup, txt_2.str)
println('${cstring_to_vstring(addto)}')
 
// Must manually free memory or program can hang because unsafe.
free(dup)
free(addto)
}
exit(0)
}
</syntaxhighlight>
 
{{out}}
<pre>
Hello World!
Hello World! Let's Wish for Peace!
</pre>
 
=={{header|Wren}}==
Although RC task solutions are usually written for execution by Wren CLI, the language's main purpose is for embedding and the embedding API is written in C. It is therefore a relative easy matter to call a C function from Wren after first embedding the latter in a suitable C program.
291

edits