【问题标题】:printf() within a C-function outputs wrong result in Python when using ctypes使用 ctypes 时,C 函数中的 printf() 在 Python 中输出错误结果
【发布时间】:2017-11-08 17:04:56
【问题描述】:

我有以下问题。任何帮助将不胜感激:)

我正在尝试使用 ctypes 从 Python 调用 C 函数。我已成功将共享库(Windows 上的 .dll 与 MS Visual Studio 2017)共享到 Python 3.6.3。

当我尝试调用以下函数时出现问题:

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

我希望在 Python 解释器中看到输出为 'hello world !!'当我执行

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

目前我在执行上述代码时没有看到任何输出(因为 restype 为 None)。

运行脚本后 Python 解释器的预期输出:

>>> hello world !!

有什么想法吗??

【问题讨论】:

  • 您可能正在使用 IDE 并且 stdout 被重定向或替换。在 Windows 控制台中运行它,您应该会看到输出。
  • @Mark Tolonen,但我想查看 python 解释器的输出。这可能吗?如果可以,我应该做些什么改变?
  • 取决于您使用的是什么。您的 IDE 可能无法实现。您是否尝试在控制台中运行 Python?
  • 如何运行 Python?还请显示整个 Python 脚本(什么是 cdll?)
  • @MarkTolonen,是的,我尝试在控制台中运行 Python 脚本并且它有效。谢谢你的帮助 !!但我仍然很想知道是否存在任何东西,是否有可能在 python 解释器中看到相同的输出。

标签: python c printf ctypes


【解决方案1】:
  • 你的“你好世界!!”无论如何都应该打印。也许标准输出被重定向到某个你看不到的地方?或者行缓冲是一个问题,请在调用 printf() 之后尝试 fflush(stdout)

  • 这些函数的默认返回类型是int。您没有明确返回一个 int,因此只是将某个恰好在某个 cpu 寄存器中的值作为返回值。可能是printf() 的返回值,在这种情况下为 14(打印的字符数)

  • 您可以通过发出:mydll.printFunc.restype = None 将返回类型更改为void,然后您不应将任何整数作为 (python) 函数调用的返回值。

  • 1234563相应地输入:

.

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

在你的 python 解释器中:

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

【讨论】:

  • 您好@Ctx,我在 C 程序中的 printf() 之后插入了“fflush(stdout)”,并且还将 mydll.printFunc.restype 更改为 None。不幸的是,我仍然看到输出为整数,即 26。请问还有其他建议吗?
  • @Vandith hm,您可以使用输入和输出来 c&p 实际会话并在上面的问题中对其进行编辑吗?
  • 对不起;更改后没有输出。我提到的输出 26 来自其他函数。
  • @n.m.我已将代码缩减为我所拥有的和预期的行为。如果您对此有解决方案,请告诉我。谢谢!
  • @Vandith 我已经更新了答案,也许这就是你想要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多