As part of the JNI, I do not provide automatic garbage collection for external resources, but there will be wrappers providing bindings for the language.
Python , API C
python
. Py_INCREF()
PyObject * ,
, , Py_DECREF()
.
(, -
, ).
Java (JVM) ,
JNI, . Python,
(*env)->DeleteLocalRef() (*env)->Release...() (
),
JNI.
, C foo:
typedef struct {
char * bar;
} foo;
foo * foo_new(const char * bar);
void foo_delete(foo * self);
#include <stdlib.h>
#include <string.h>
#include "foo.h"
foo * foo_new(const char * bar) {
foo * self = malloc(sizeof(foo));
if (self == NULL) {
return NULL;
}
memset(self, 0, sizeof(foo));
size_t bar_len = strlen(bar);
char * bar_copy = malloc(sizeof(char) * (bar_len + 1));
if (bar_copy == NULL) {
foo_delete(self);
return NULL;
}
strncpy(bar_copy, bar, bar_len);
bar_copy[bar_len] = '\0';
self->bar = bar_copy;
return self;
}
void foo_delete(foo * self) {
if (self == NULL) {
return;
}
if (self->bar != NULL) {
free(self->bar);
self->bar = NULL;
}
free(self);
}
, Python foo,
Python,
. Python
Python.
typedef struct {
PyObject_HEAD;
foo * foo;
} PyFoo;
static PyObject * PyFoo_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
const char * bar;
if (!PyArg_ParseTuple(args, "s", &bar)) {
return NULL;
}
PyFoo * self;
self = (PyFoo *)type->tp_alloc(type, 0);
if (self == NULL) {
return NULL;
}
self->foo = foo_new(bar);
if (self->foo == NULL) {
Py_DECREF(self);
return NULL;
}
return (PyObject *)self;
}
static void PyFoo_dealloc(PyFoo * self) {
foo_delete(self->foo);
self->ob_type->tp_free((PyObject *)self);
}
static PyObject * PyFoo_bar(PyFoo * self) {
return (PyObject *)PyString_FromString(self->foo->bar)
}
static PyMethodDef PyFoo_methods[] = {
{"foo", (PyCFunction)PyFoo_bar, METH_NOARGS, "Returns foo."},
{NULL},
};
foo Java, Java
. JNI
(, ,
). (
Java),
.
public class Foo {
private long foo_ptr;
public Foo(String bar) {
this.foo_ptr = this.foo_new(bar)
}
protected void finalize() {
this.foo_delete(this.foo_ptr);
}
public String getBar() {
return this.foo_bar(this.foo_ptr);
}
static {
System.loadLibrary("javafoo");
}
private native long foo_new(String bar);
private native void foo_delete(long foo_ptr);
private native String foo_bar(long foo);
}
#include <jni.h>
#include "foo.h"
JNIEXPORT jlong JNICALL Java_Foo_foo_new(JNIEnv * env, jstring jbar) {
char * bar = (*env)->GetStringUTFChars(env, jbar, NULL);
if (bar == NULL) {
return 0;
}
foo * self = foo_new(bar);
if (self == NULL) {
(*env)->ReleaseStringUTFChars(env, jbar, bar);
return 0;
}
(*env)->ReleaseStringUTFChars(env, jbar, bar);
return (jlong)self;
}
JNIEXPORT void JNICALL Java_Foo_foo_delete(JNIEnv * env, jlong foo_ptr) {
foo * self = (foo *)foo_ptr;
foo_delete(self);
}
JNIEXPORT jstring JNICALL Java_Foo_foo_bar(JNIEnv * env, jlong foo_ptr) {
foo * self = (foo *)foo_ptr;
jstring jbar = (*env)->NewStringUTF(env, self->bar);
return jbar;
}
. : , , .