使用SWIG模块遇TypeError:参数1类型应为unsigned char const *求助
TypeError: argument 1 of type 'unsigned char const *' in SWIG Let's break down how to resolve this type mismatch issue when passing Python data to your SWIG-wrapped C function.
The Root Cause
SWIG doesn't automatically map Python's native types (like lists, bytes, or bytearray) to C's const unsigned char * pointer type. When you try to pass a Python object directly to dump(), SWIG can't convert it to the expected C pointer, hence the type error.
Solution 1: Use SWIG's Array Helper (carrays.i)
This approach creates a wrapper class for C-style arrays, letting you pass typed arrays from Python to C easily.
Step 1: Modify your example.i file
Add the array helper include and declare an array class for unsigned char:
%module example %{ #include "example.h" %} %include "carrays.i" %array_class(unsigned char, UnsignedCharArray); %include "example.h"
Step 2: Use the array in Python
You can now create an UnsignedCharArray instance, populate it, and pass its underlying pointer to dump():
import example # Create an array of 10 unsigned chars buffer = example.UnsignedCharArray(10) # Set values (indexing works like a Python list) buffer[0] = 0x01 buffer[1] = 0x02 # ... populate other indices as needed # Pass the array's C pointer and pitch to dump() example.dump(buffer.cast(), 10)
Solution 2: Add a Typemap for bytes/bytearray
If you prefer using Python's built-in bytes or bytearray types directly, add a typemap to tell SWIG how to convert these objects to const unsigned char *.
Step 1: Update example.i with the typemap
Add this typemap before including your header:
%module example %{ #include "example.h" %} // Typemap to convert Python bytes/bytearray to const unsigned char* %typemap(in) const unsigned char *buffer { if (!PyBytes_Check($input) && !PyByteArray_Check($input)) { PyErr_SetString(PyExc_TypeError, "Expected bytes or bytearray object"); return NULL; } $1 = (unsigned char *)(PyBytes_Check($input) ? PyBytes_AsString($input) : PyByteArray_AsString($input)); } %include "example.h"
Step 2: Pass bytes directly in Python
Now you can use Python's native bytes type without extra wrapper classes:
import example # Pass a bytes object and pitch to dump() example.dump(b'\x00\x01\x02\x03', 4) # Or use a bytearray buf = bytearray([0x04, 0x05, 0x06]) example.dump(buf, 3)
Notes
- If you're passing a list of integers (0-255), you'll need an extra step to convert it to
bytesfirst (e.g.,bytes(my_int_list)). - Always ensure the
pitchvalue matches the length of your buffer to avoid out-of-bounds access in the C code.
内容的提问来源于stack exchange,提问作者BPL

