07-24-2023, 09:10 AM
I am trying to send 2 strings from Python (3.2) to C using ctypes. This is a small part of my project on my Raspberry Pi. To test if the C function received the strings correctly, I place one of them in a text file.
**Python code**
<!-- language: lang-python -->
string1 = "my string 1"
string2 = "my string 2"
# create byte objects from the strings
b_string1 = string1.encode('utf-8')
b_string2 = string2.encode('utf-8')
# send strings to c function
my_c_function(ctypes.create_string_buffer(b_string1),
ctypes.create_string_buffer(b_string2))
**C code**
<!-- language: lang-c -->
void my_c_function(const char* str1, const char* str2)
{
// Test if string is correct
FILE *fp = fopen("//home//pi//Desktop//out.txt", "w");
if (fp != NULL)
{
fputs(str1, fp);
fclose(fp);
}
// Do something with strings..
}
**The problem**
Only the first letter of the string appears in the text file.
I've tried many ways to convert the Python string object with ctypes.
- ctypes.c_char_p
- ctypes.c_wchar_p
- ctypes.create_string_buffer
With these conversions I keep getting the error "wrong type" or "bytes or integer address expected instead of str instance".
I hope someone can tell me where it goes wrong.
Thanks in advance.
**Python code**
<!-- language: lang-python -->
string1 = "my string 1"
string2 = "my string 2"
# create byte objects from the strings
b_string1 = string1.encode('utf-8')
b_string2 = string2.encode('utf-8')
# send strings to c function
my_c_function(ctypes.create_string_buffer(b_string1),
ctypes.create_string_buffer(b_string2))
**C code**
<!-- language: lang-c -->
void my_c_function(const char* str1, const char* str2)
{
// Test if string is correct
FILE *fp = fopen("//home//pi//Desktop//out.txt", "w");
if (fp != NULL)
{
fputs(str1, fp);
fclose(fp);
}
// Do something with strings..
}
**The problem**
Only the first letter of the string appears in the text file.
I've tried many ways to convert the Python string object with ctypes.
- ctypes.c_char_p
- ctypes.c_wchar_p
- ctypes.create_string_buffer
With these conversions I keep getting the error "wrong type" or "bytes or integer address expected instead of str instance".
I hope someone can tell me where it goes wrong.
Thanks in advance.