Last active
August 8, 2023 22:58
-
-
Save Overdrivr/cdd58cea15d7e28c50ea to your computer and use it in GitHub Desktop.
Pass and return structs (by copy) between C and Python using CFFI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from cffi import FFI | |
ffi = FFI() | |
ffi.cdef(""" | |
typedef struct T T; | |
struct T | |
{ | |
int a; | |
float b; | |
}; | |
void pass_a_struct(T somedata); | |
T get_a_struct(); | |
""" | |
) | |
# Compile the C sources to produce the following .dll (or .so under *nix) | |
lib = ffi.dlopen("somelib.dll") | |
# Create a new C struct of type T | |
fooStruct = ffi.new("struct T *") | |
# Using struct fields defined in C code is as simple as this | |
fooStruct.a = 12; | |
fooStruct.b = 3.5; | |
# To pass the struct you need to dereference it (like you would in C) | |
lib.pass_a_struct(fooStruct[0]) | |
# To get the struct use simple assignement | |
fooStruct = lib.get_a_struct() | |
# And that's it | |
print("Got : ",fooStruct) | |
print("T.a",fooStruct.a) | |
print("T.b",fooStruct.b) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "somelib.h" | |
static T myStruct; | |
void pass_a_struct(T somedata) | |
{ | |
myStruct.a = somedata.a * 2; | |
myStruct.b = somedata.b / 3.f; | |
} | |
T get_a_struct() | |
{ | |
return myStruct; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef SOMELIB_H_ | |
#define SOMELIB_H_ | |
typedef struct T T; | |
struct T | |
{ | |
int a; | |
float b; | |
}; | |
// pass a struct | |
void pass_a_struct(T somedata); | |
// get back a struct | |
T get_a_struct(); | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment