diff --git a/integration_tests/test_c_interop_02.py b/integration_tests/test_c_interop_02.py index 893360a005..a0d1fc2b99 100644 --- a/integration_tests/test_c_interop_02.py +++ b/integration_tests/test_c_interop_02.py @@ -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 @@ -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() diff --git a/integration_tests/test_c_interop_02b.c b/integration_tests/test_c_interop_02b.c index ded7af3a2c..2dfde29304 100644 --- a/integration_tests/test_c_interop_02b.c +++ b/integration_tests/test_c_interop_02b.c @@ -1,3 +1,5 @@ +#include + #include "test_c_interop_02b.h" double f_f64_f64(double x) { @@ -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); +} diff --git a/integration_tests/test_c_interop_02b.h b/integration_tests/test_c_interop_02b.h index fdf677aa9f..331f8a9103 100644 --- a/integration_tests/test_c_interop_02b.h +++ b/integration_tests/test_c_interop_02b.h @@ -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 diff --git a/src/runtime/ltypes/ltypes.py b/src/runtime/ltypes/ltypes.py index 3a9e8aa2e1..89de4f3992 100644 --- a/src/runtime/ltypes/ltypes.py +++ b/src/runtime/ltypes/ltypes.py @@ -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): @@ -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)