Alvin
Alvin

Reputation: 45

access python ctypes structure from c shared library

I wrote a python code to passing ctypes structure to c library function

python code:

from ctypes import *

class Info(Structure):
   _field_ = [("input",c_int),
              ("out",c_int)]

info = Info()

info.input = c_int(32)
info.out = c_int(121)

lib = CDLL("./sharedLib.so").getVal
a = lib(byref(info))

c code :

#include <stdio.h>

struct info{
    int input;
    int out;
};

void getVal(struct info *a){
    printf("in = %i \n", a->input);
    printf("out = %i \n", a->out);
}

compile it using command : gcc -shared -fPIC -o sharedLib.so sharedLib.c

output :

in = 0 
out = 0 

My problem is, why output is different from value that i set in python code. Is there any solution ? Im in 32-bit environment

Upvotes: 1

Views: 1592

Answers (2)

interjay
interjay

Reputation: 110108

In the ctypes structure definition, you wrote _field_ instead of _fields_. As a result, the fields aren't translated to their C equivalents.

Upvotes: 6

PaulMcG
PaulMcG

Reputation: 63709

Try adding:

lib.argtypes = [POINTER(Info)]

before calling lib.

Upvotes: 1

Related Questions