Use SWIG to generate a proxy class for a C struct and a wrapper class for a pointer to the C struct

我只是一个虾纸丫 提交于 2019-12-25 01:48:40

问题


I'm trying to get SWIG to generate Java glue code for me to wrap a C library with.

I have a C header file that looks (roughly) like this:

struct MyDatabase;
typedef struct MyDatabase MyDatabase;

struct MyDatabase {
  const void *db;
};

struct MyDatabase *open_database(char *name);

I've written my SWIG interface file like this:

%module database

%{
#include "database.h"
%}

struct MyDatabase;

%nodefaultctor MyDatabase;
%nodefaultdtor MyDatabase;
struct MyDatabase {
  const void *db;
};

struct MyDatabase *open_database(char *name);

%include "cpointer.i"
%pointer_functions(MyDatabase, MyDatabasePtr)

I'm then running:

swig -java -package com.test.db -outdir com/test/db -o database.c database.i

What I want to be able to do in my Java code is something like this:

SWIGTYPE_p_MyDatabase dbPointer = open_database("some_db_name");
MyDatabase db = MyDatabasePtr_value(dbPointer);

Or something like that. Essentially I want to be able to call the C library's open_database, which will return a pointer to MyDatabase, and then be able to get at the underlying MyDatabase instance in order to access properties on it etc.

The problem I'm facing is that I can't seem to get SWIG to generate a proxy class for MyDatabase, as well as generating a wrapper class for a pointer to MyDatabase (i.e. SWIGTYPE_p_MyDatabase).

I might be coming at this completely the wrong way but from what I've read so far it seems like the interface file above should let me do that, but it doesn't, so clearly I'm missing something!


UPDATE 1:

If I add %include "database.h" to database.i then I get both MyDatabase and SWIGTYPE_p_MyDatabase being generated. However, the pointer function that I was hoping to be generated by %pointer_functions(MyDatabase, MyDatabasePtr) ends up producing this:

public static SWIGTYPE_p_MyDatabase MyDatabaseHandle_value(SWIGTYPE_p_MyDatabase obj) {
    return new SWIGTYPE_p_MyDatabase(databaseJNI.MyDatabaseHandle_value(SWIGTYPE_p_MyDatabase.getCPtr(obj)), true);
}

which isn't very useful, as far as I can tell. I was expecting the function to be:

public static MyDatabase MyDatabaseHandle_value(SWIGTYPE_p_MyDatabase obj) {
    return new MyDatabase(databaseJNI.MyDatabaseHandle_value(SWIGTYPE_p_MyDatabase.getCPtr(obj)), true);
}

Manually changing the function to the one above does seem to work, but that's not really a long-term solution, nor in the spirit of what SWIG is really useful for 😊

来源:https://stackoverflow.com/questions/54808136/use-swig-to-generate-a-proxy-class-for-a-c-struct-and-a-wrapper-class-for-a-poin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!