0
votes

I'm trying to make a object-oriented, slightly polymorphic interface in a C project, and export such an interface to Lua (unfortunately, the language requirements are fairly fixed for the short term) using SWIG. Here's an example of an interface that I want to generate a wrapper for:

// In BaseObject.h
typedef struct BaseObject {
  int member;
  int (*foo)(struct BaseObject *self, int param);
} BaseObject;

// Polymorphism:
int derived_foo(struct BaseObject *self, int param) {
  return param * self->member;
}

// Making a "DerivedObject"
BaseObject *obj = malloc(sizeof(BaseObject));
obj->member = 20;
printf("%d\n", obj->foo(obj, 40)); // "800"

This is basically to simulate OO-style polymorphism in a pure C context. I would now like to call methods of this struct from Lua using SWIG. The best I've come up with so far is something like this:

// BaseObject.i
%module BaseObject
%{
#include "BaseObject.h"
%}

typedef struct BaseObject {
  int foo(struct BaseObject *self, int param);
} BaseObject;

i.e. using SWIG's "member functions" support. This, however, tacks on an extra "self" reference to the beginning, so that I have to pass the "self" reference twice in Lua:

-- bo is a BaseObject
bo.foo(bo, bo, 20)

-- this would be ideal, but isn't what I get right now:
bo.foo(bo, 20)
-- equivalently:
bo:foo(20)

Removing the struct BaseObject * param in the SWIG interface file almost works but breaks the generated wrapper, since SWIG calls the "member function" as follows:

// BaseObject_wrap.c
// arg1 = the BaseObject
// arg2 = param
result = (int)(arg1)->supports(arg2);

Has anyone gotten this type of thing to work before? Thanks in advance for all responses! :)

1

1 Answers

0
votes

Try this:

typedef struct BaseObject {
  static int foo(struct BaseObject *self, int param);
} BaseObject;