Call a function in a shared library: Difference between revisions

Content added Content deleted
m (added whitespace before the TOC, corrected the sub-section "Related tasks" to a task section.)
(Added Kotlin)
Line 1,049: Line 1,049:
ccall( (:clock, "libc"), Int32, ())</lang>
ccall( (:clock, "libc"), Int32, ())</lang>
For more information, see here [http://docs.julialang.org/en/latest/manual/calling-c-and-fortran-code.html]
For more information, see here [http://docs.julialang.org/en/latest/manual/calling-c-and-fortran-code.html]

=={{header|Kotlin}}==
{{trans|C}}
{{Works with|Ubuntu 14.04}}

This is the C code to produce fakeimglib.so:
<lang C>#include <stdio.h>
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
{
static int handle = 100;
fprintf(stderr, "opening %s\n", s);
return handle++;
}</lang>
And this is the Kotlin code to dynamically load the .so file and call the 'openimage' function - or if the .so file (or the function itself) is not available, to call the internal version of the function:
<lang scala>// Kotlin Native version 0.5

import kotlinx.cinterop.*
import platform.posix.*
import platform.linux.*

typealias Func = (String)-> Int

var handle = 0

fun myOpenImage(s: String): Int {
fprintf(stderr, "internal openImage opens %s...\n", s)
return handle++
}

fun main(args: Array<String>) {
var imgHandle: Int
val imglib = dlopen("./fakeimglib.so", RTLD_LAZY)
if (imglib != null) {
val fp = dlsym(imglib, "openimage")
if (fp != null) {
val extOpenImage: CPointer<CFunction<Func>> = fp.reinterpret()
imgHandle = extOpenImage("fake.img")
}
else {
imgHandle = myOpenImage("fake.img")
}
dlclose(imglib)
}
else {
imgHandle = myOpenImage("fake.img")
}
println("opened with handle $imgHandle")
}</lang>

{{out}}
<pre>
Same as C entry
</pre>


=={{header|Lingo}}==
=={{header|Lingo}}==