简体   繁体   English

Python-将字符传递到C库

[英]Python - Passing character to C library

I've got quite the trouble running a program on Linux i wrote. 我在编写的Linux上运行程序遇到了很多麻烦。 Since it's quite a large program i won't post the whole code but only the part that gets me confused. 由于它是一个很大的程序,因此我不会发布整个代码,而只会发布让我感到困惑的部分。 I've got a library, written in C++ and compiled on Linux Ubuntu, which does some work and prints an incoming character to the console like this: 我有一个用C ++编写并在Linux Ubuntu上编译的库,该库可以完成一些工作,并将输入的字符打印到控制台,如下所示:

bool PostCommand( void* pParam, char c, char* szRet, int nLength, int nBlockTime )
{
    printf("Got: %d", c);
    //do some work
    return true;
}

The whole thing compiles well and my Python program is able to call the function: 整个程序编译良好,我的Python程序能够调用该函数:

# -*- coding: ascii -*-
from ctypes import cdll,c_char,create_string_buffer,...#don't want to list 'em all
m_DLL = cdll.LoadLibrary("./libaddonClient.so")
PostCommand = m_DLL.PostCommand
PostCommand.argtype = [c_void_p,c_char,c_char_p,c_int,c_int]
PostCommand.restype = c_bool

print ord('1')
sz = create_string_buffer(20);
#pObject was generated prior and works fine
PostCommand( pObject, '1', sz, 20, 1 )

The console output looks like 控制台输出看起来像

49
Got: -124

My question is how the 49 could change into -124. 我的问题是49怎样变成-124。 The variable isn't being changed between it's creation and the call of the C++ function or the printf, which follows right after the call. 在创建变量与调用C ++函数或调用printf之间不会更改该变量。 There are no threads accessing this function nor static variables. 没有线程访问此函数,也没有静态变量。

Your problem is in the python code, you are passing a string instead of a character, the single quotes and double quotes both work almost exactly the same in python, and -124 I presume comes perhaps from something that python interpreter does internally, try this 您的问题出在python代码中,您传递的是字符串而不是字符,单引号和双引号在python中几乎完全相同,并且-124我想这可能是python解释器内部执行的操作,请尝试

PostCommand( pObject, ord('1'), sz, 20, 1 )

What is very likely happening is that the parameter when processed by the interpreter is stored as ac string, which is a nul terminated sequence of non- nul bytes, hence a pointer is almost surely used, so -124 has to be the address of the pointer which of course requires more than a byte to be represented. 很有可能发生的是,当解释器处理该参数时,该参数以ac字符串存储,这是一个以nul终止的非nul字节序列,因此几乎肯定使用了指针,因此-124必须是指针的地址。指针,当然需要一个以上的字节来表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM