Reputation: 39
I'm wrapping some C code from an embedded system for experimenting, using SWIG and targeting Python. It's simple code, and I've stubbed out the hardware and everything is compiling fine.
The issue I've run into is that the functions I'm interested in operate on a static global 'context' variable defined at the top of the C file. I can't figure out how to have this variable instantiated by the module and be operated on by the wrapped functions.
I made some simple test files to play with, and if I declare the global variable in the module it appears in cvar, but a function which is supposed to modify this variable in its body has no effect on the cvar instance.
Is there any way to make this work, without modifying the C source files I am wrapping?
Upvotes: 1
Views: 1731
Reputation: 4725
This works
If you declare you constants extern in your header, it works fine.
Header
/* test.h */
extern float g_float;
float getMe();
Source
/* test.cpp */
#include "test.h"
float g_float = 4.0;
float getMe() {
return g_float;
}
Interface definition file
/* test.i */
%module test
%{
#include "test.h"
%}
%include "test.h"
Modify the variable using
import test
test.cvar.g_float = 4.5
test.getMe()
If you have constants declared and initialized in your header, you could add inline functions for setting/getting them and properties in your interface definition file.
A static class variable also works, but this is accessed using the class rather than cvar.
Upvotes: 3