Skip to content

Get C strings passing from Python to C #671

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions integration_tests/test_c_interop_02.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ def f_i16_i16(x: i16) -> i16:
def f_i8_i8(x: i8) -> i8:
pass

@ccall
def f_str_i32(x: str) -> i32:
pass

def test_c_callbacks():
xf64: f64
xf64 = 3.3
Expand All @@ -49,4 +53,9 @@ def test_c_callbacks():
xi8 = 3
assert f_i8_i8(xi8) == 4

s: str
s = "Hello World!"
print(f_str_i32(s))
assert f_str_i32(s) == 3

test_c_callbacks()
6 changes: 6 additions & 0 deletions integration_tests/test_c_interop_02b.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#include <string.h>

#include "test_c_interop_02b.h"

double f_f64_f64(double x) {
Expand All @@ -23,3 +25,7 @@ int16_t f_i16_i16(int16_t x) {
int8_t f_i8_i8(int8_t x) {
return x+1;
}

int32_t f_str_i32(char *x) {
return strlen(x);
}
1 change: 1 addition & 0 deletions integration_tests/test_c_interop_02b.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ int64_t f_i64_i64(int64_t x);
int32_t f_i32_i32(int32_t x);
int16_t f_i16_i16(int16_t x);
int8_t f_i8_i8 (int8_t x);
int32_t f_str_i32(char *x);


#endif // TEST_C_INTEROP_02B
18 changes: 18 additions & 0 deletions src/runtime/ltypes/ltypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ def convert_type_to_ctype(arg):
return ctypes.c_int8
elif arg == CPtr:
return ctypes.c_void_p
elif arg == str:
#return ctypes.POINTER(ctypes.c_char)
return ctypes.c_void_p
elif arg is None:
raise NotImplementedError("Type cannot be None")
elif isinstance(arg, Array):
Expand Down Expand Up @@ -176,6 +179,21 @@ def get_crtlib_path():
def __call__(self, *args, **kwargs):
if len(kwargs) > 0:
raise Exception("kwargs are not supported")
new_args = []
for arg in args:
if isinstance(arg, str):
# wrap strings into c_char_p
#b = arg.encode("utf-8")
#new_args.append(ctypes.c_char_p(bytes(arg, "utf-8")))
#new_args.append(bytes(arg, "utf-8"))
b = "xxxxxxx"
b = ctypes.create_string_buffer(str.encode(b))
print(type(b))
new_args.append(b)
else:
new_args.append(arg)
print(self.cf.argtypes)
print(new_args)
return self.cf(*args)


Expand Down