I want to wrap a static member variable of a struct, such that when it is read or written from Python, a custom get/set function is called on the C++ side. The following works, for a non-static variable. This is foo.h
:
#ifndef FOO_H
#define FOO_H
#include <iostream>
struct Foo
{
static int bar() { std::cout << "Foo::bar()\n"; return 0; }
};
#endif
foo.i
looks as follows:
%module foo
%{
#include "foo.h"
%}
struct Foo
{
};
%extend Foo {
int i;
}
%{
int Foo_i_get(Foo* obj) {
return Foo::bar();
}
void Foo_i_set(Foo* obj, int i) {}
%}
This sort of works, in Python I can do:
import foo
f = foo.Foo()
f.i
This triggers Foo::bar()
being called. What I want to achieve is the following having the same behavior:
import foo
foo.Foo.i
This does not work, since i
is not a class property. I naively tried changing the following in the .i
file:
%extend Foo {
static int i;
}
This gives compilation errors in the following wrapper code generated by SWIG:
SWIGINTERN PyObject *Swig_var_Foo_i_get(void) {
PyObject *pyobj = 0;
pyobj = SWIG_From_int((int)(Foo::i));
return pyobj;
}
This is the error message given by g++
:
foo_wrap.c: In function ‘PyObject* Swig_var_Foo_i_get()’:
foo_wrap.c:3208:31: error: ‘i’ is not a member of ‘Foo’
pyobj = SWIG_From_int((int)(Foo::i));
So obviously this is not the right approach. How can I extend a struct with a static variable, with custom setters and getters?
this might work: foo.i looks as follows:
%module foo
%{
#include "foo.h"
%}
%include "foo.h"
%extend Foo {
int get_i(){ return Foo::bar(); }
%pythoncode %{
i = property(get_i)
%}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.