I wanted to exchange strings between a C and a Python program. I followed the template of Python using ctypes to pass a char * array and populate results (which is slightly different as it only communicates an array of strings from C to Python). The C program given below:
//simplegmp.c
#include<gmp.h>
#include <stdio.h>
#include <ctype.h>
#include<string.h>
void Cnumfunc(char** sent, char** recd)
{
printf("This is the string %s\n",*sent);
mpz_t p1;
mpz_init(p1);
mpz_set_str(p1,*sent,10);
gmp_printf("Value of the gmp number is : %Zd \n", p1);
mpz_add_ui(p1,p1,1);// add 1 and send back
mpz_get_str(*recd,10,p1);
}
Compilation command for C program:
gcc -shared -o libsimple.so -fPIC simplegmp.c -lgmp
Now the python program:
#simplegm.py
import ctypes
libsimplegmp=ctypes.CDLL("./libsimple.so")
string_sent=ctypes.create_string_buffer(8)
string_recd=ctypes.create_string_buffer(8)
ptr_to_sent=ctypes.c_char_p(ctypes.addressof(string_sent))
ptr_to_recd=ctypes.c_char_p(ctypes.addressof(string_recd))
#libsimplegmp.connect()
string_sent="8374890"
libsimplegmp.Cnumfunc(ptr_to_sent,ptr_to_recd)
returnednum=ptr_to_recd.value
print("this is",returnednum)
This gives me the following:
This is the string (null)
Segmentation fault (core dumped)
I am new to this kind of programming and any help is much appreciated. Thanks.
(Question edited to latest details)
mapdoes?ctypes.addressofgets the address... and how many things do you want the address of? What do you thinkmapis for, and how do you expect it to help solve your problem? When you looked in the documentation forctypes.addressof, did the examples involve usingmap? When you sawmapin the code at the other answer you linked, did you understand why the code uses it? (Hint: in that code, how is thestring_buffersdata structured? Do you see how that differs from your data?)