简体   繁体   English

使用ctypes时,C函数中的printf()在Python中输出错误的结果

[英]printf() within a C-function outputs wrong result in Python when using ctypes

I have the following problem. 我有以下问题。 Any help would be appreciated :) 任何帮助,将不胜感激 :)

I am trying to call a C function from Python using ctypes. 我正在尝试使用ctypes从Python调用C函数。 I have been successful in sharing the shared library (.dll on Windows with MS Visual Studio 2017) to Python 3.6.3. 我已成功共享了共享库(在Windows上使用MS Visual Studio 2017的.dll)到Python 3.6.3。

There is a problem when I try to call the following function: 当我尝试调用以下函数时出现问题:

__declspec(dllexport) void printFunc()
{
    printf("hello world !!");
    //fflush(stdout);
}

I would like to see the output at Python interpreter as 'hello world !!' 我希望将Python解释器的输出显示为“ hello world !!”。 when I execute 当我执行

mydll = cdll.LoadLibrary('path\\to\\sharedLibrary.dll')
mydll.printFunc.restype = None
mydll.printFunc()

Currently I see no output (because, the restype is None) when I execute the above code. 当前,当我执行上述代码时,我看不到任何输出(因为restype为None)。

Expected output at Python interpreter after running the script: 运行脚本后,Python解释器的预期输出:

>>> hello world !!

Any ideas please ?? 有什么想法吗??

  • Your "hello world !!" 你的“你好,世界!” should be printed in any case. 在任何情况下都应打印。 Maybe stdout is redirected to somewhere, where you can't see it? 也许stdout被重定向到您看不到的地方? Or line buffering is an issue, try fflush(stdout) after your printf() call. 或行缓冲是一个问题,请在调用printf()之后尝试fflush(stdout)

  • The default return type for those functions is int . 这些函数的默认返回类型为int You do not explicitely return an int, so just some value which happened to be in some cpu register is taken as return value. 您没有显式地返回int,因此只将某些cpu寄存器中的某个值作为返回值。 Chances are, that it is the return value of the printf() , which is 14 in this case (the number of characters printed) 很有可能是printf()的返回值,在这种情况下为14(打印的字符数)

  • You can change the return type to void by issuing: mydll.printFunc.restype = None , then you shouldn't observe any integer as return value of the (python) function call. 您可以通过发出以下mydll.printFunc.restype = None将返回类型更改为voidmydll.printFunc.restype = None ,那么您不应观察到任何整数作为(python)函数调用的返回值。

  • If you want to have the output at your python interpreter instead of stdout, you will have to return the string from your function instead of passing it to printf() and adjust the return type accordingly: 如果要在python解释器上输出而不是stdout,则必须从函数中返回字符串,而不是将其传递给printf()并相应地调整返回类型:

.

 __declspec(dllexport) char *printFunc() {
     return "hello world !!";
 }

And in your python interpreter: 在您的python解释器中:

>>> from ctypes import *
>>> mydll = cdll.LoadLibrary('path\\to\\sharedLibrary.dll')
>>> mydll.printFunc.restype = c_char_p
>>> mydll.printFunc()
'hello world !!'

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

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