Use another language to call a function: Difference between revisions

Added Kotlin
(Add Java using Java Native Interface.)
(Added Kotlin)
Line 793:
clean:
rm -f calljava main.o query-jni.o Query.class</lang>
 
=={{header|Kotlin}}==
Reverse interop (calling Kotlin from C) was added to Kotlin Native in version 0.5 and the following shows how to perform this task on Ubuntu Linux.
 
First we compile the following Kotlin source file (Query.kt) using the '-platform dynamic' flag:
<lang scala>// Kotlin Native v0.6
 
import kotlinx.cinterop.*
import platform.posix.*
 
fun query(data: CPointer<ByteVar>, length: CPointer<size_tVar>): Int {
val s = "Here am I"
val strLen = s.length
val bufferSize = length.pointed.value
if (strLen > bufferSize) return 0 // buffer not large enough
for (i in 0 until strLen) data[i] = s[i].toByte()
length.pointed.value = strLen.signExtend<size_t>()
return 1
}</lang>
 
This produces the dynamic library, libQuery.so, and the C header file libQuery_api.h:
<lang c>#ifndef KONAN_LIBQUERY_H
#define KONAN_LIBQUERY_H
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned char libQuery_KBoolean;
typedef char libQuery_KByte;
typedef unsigned short libQuery_KChar;
typedef short libQuery_KShort;
typedef int libQuery_KInt;
typedef long long libQuery_KLong;
typedef float libQuery_KFloat;
typedef double libQuery_KDouble;
typedef void* libQuery_KNativePtr;
struct libQuery_KType;
typedef struct libQuery_KType libQuery_KType;
 
typedef struct {
/* Service functions. */
void (*DisposeStablePointer)(libQuery_KNativePtr ptr);
void (*DisposeString)(const char* string);
libQuery_KBoolean (*IsInstance)(libQuery_KNativePtr ref, const libQuery_KType* type);
 
/* User functions. */
struct {
struct {
libQuery_KInt (*query)(void* data, void* length);
} root;
} kotlin;
} libQuery_ExportedSymbols;
extern libQuery_ExportedSymbols* libQuery_symbols(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* KONAN_LIBQUERY_H */</lang>
 
We now compile a slightly modified version of the C program required for this task, linking to the above library, and 'including' the header file:
<lang c>#include <stdio.h>
#include <stdlib.h>
#include "libQuery_api.h"
 
static int Query (char * Data, size_t * Length)
{
return libQuery_symbols() -> kotlin.root.query(Data, Length);
}
 
int main (int argc, char * argv [])
{
char Buffer [1024];
size_t Size = sizeof (Buffer);
if (0 == Query (Buffer, &Size))
{
printf ("failed to call Query\n");
}
else
{
char * Ptr = Buffer;
while (Size-- > 0) putchar (*Ptr++);
putchar ('\n');
}
}</lang>
 
which when executed produces the expected output:
<pre>
Here am I
</pre>
 
=={{header|Lisaac}}==
9,479

edits