SWIG:字符串没有被完全复制或显示?
我需要将指向字符数组的指针发送给我的函数之一。为了生成这个 char*,我在我的一个 c 文件中使用这个函数,这样调用它的
charPtr = myProj.strAll ( 8 );
地方是 strAll:
char * strAll ( int size ) {
return malloc( sizeof( char ) * size );
}
然后我将 charPtr 传递到一个像这样的函数中:
myProj.Populate ( char* dataIn, char* dataOut, maxLen );
Populate 将 dataIn 复制到 dataOut,使用 maxLen 作为大小限制。它使用 memcpy 通过如下方式复制它:
memcpy ( dataOut, dataIn, maxLen);
用法:
myProj.Populate ( "ABCD1234", charPtr, 8 ); //maxLen is the # of bytes I've allocated for charPtr.
但是,当我告诉 python 打印 charPtr 时,它只会打印 ABC。
预期:
>>charPtr
'ABCD1234'
>>print charPTr
ABCD1234
实际:
>>charPtr
'ABC'
>>print charPTr
ABC
有谁知道发生了什么?
I need to send a pointer to a character array to one of my functions. To produce this char*, I use this function in one of my c files such that is called like this
charPtr = myProj.strAll ( 8 );
where strAll is:
char * strAll ( int size ) {
return malloc( sizeof( char ) * size );
}
I then pass charPtr into a function like this:
myProj.Populate ( char* dataIn, char* dataOut, maxLen );
Populate copies dataIn into dataOut, using maxLen as the size restriction. It uses memcpy to copy it over through something like this:
memcpy ( dataOut, dataIn, maxLen);
Usage:
myProj.Populate ( "ABCD1234", charPtr, 8 ); //maxLen is the # of bytes I've allocated for charPtr.
However, when I tell python to print charPtr out, it will only print ABC.
Expected:
>>charPtr
'ABCD1234'
>>print charPTr
ABCD1234
Actual:
>>charPtr
'ABC'
>>print charPTr
ABC
Does anyone know what is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ABCD1234
有 8 个字符。但您还应该为终止字符\0
提供一个额外的字节。每个 C 字符串都应以\0
终止。charPtr
应指向可容纳 9 个字符的位置,其中最后一个字符用于放置终止字符。我不确定为什么您只分配 5 个位置来尝试复制 8 个字符长的字符串。
ABCD1234
has 8 characters. But you should also provide an extra byte for the termination character\0
. Every C string should be terminated by\0
.charPtr
should be pointing to a location which can accommodate 9 characters out of which the last is to place the termination character.And I amn't sure why are you just allocating 5 locations where you are trying to copy a string of 8 characters long.