Python:将数据从扭曲的套接字读取到 SWIG-ed 结构中

标签 python c sockets twisted swig

我正在编写一个 Python 客户端来连接到一个用 C 语言编写的服务器,该服务器以二进制结构发送状态。我已经用 SWIG 包装了 C 结构,但我需要将套接字返回的数据作为 C 结构来处理。特别是,我想将传递给 dataReceived() 的数据转换为 iwrf_ui_task_operations 结构。

我是否需要编写(和 SWIG)传递“数据”并返回 iwrf_ui_task_operations 结构的辅助函数?

这是一个简单的测试程序:

from twisted.internet import reactor, protocol
import syscon_interface


class SysconClient(protocol.Protocol):
    """Once connected, receive messages from syscon."""

    def connectionMade(self):
        print "connectionMade"

    def dataReceived(self, data):
        "As soon as any data is received, write it out."
        # this constructor does not accept 'data' as an argument  :-(
        to = syscon_interface.iwrf_ui_task_operations_t()  
        print "Server said:", data

    def connectionLost(self, reason):
        print "connection lost"

class SysconClientFactory(protocol.ClientFactory):
    protocol = SysconClient

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        reactor.stop()


# this connects the protocol to a server running on port 2515
def main():
    f = SysconClientFactory()
    reactor.connectTCP("localhost", 2515, f)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()       

最佳答案

你不想这样做。传递给 dataReceived 的数据是 TCP 段,而不是协议(protocol)消息。因此,您可能会收到您的部分结构,或全部结构,或多个结构,或从结构中间开始的数据。

参见 this Twisted FAQ .

此外,您根本不想这样做。不同的 C 编译器可以完全有效地为这个结构生成不同的布局,并且你的平台的字节顺序会受到影响,这通常是一个糟糕的场景。

如果你打算这样做(并且根据你的问题的框架,我假设你必须这样做),首先你需要确保你的确切工具链版本(C 编译器版本,SWIG 版本,Python 版本、Python 构建选项等)都完全同步。然后你需要写一个成帧协议(protocol),like those in twisted.protocols.basic ,它处理基于 sizeof(iwrf_ui_task_operations_t) 的固定宽度记录,然后一旦你把它分开,一个包装函数接受一个 char* 数据 和一个int length 并构造您的结构将是合乎逻辑的下一步。

最后,不要使用 SWIG,使用 CFFI .编写绑定(bind)更容易,更易于移植到其他运行时(例如,PyPy 实际上可以将您的调用 JIT 到 C 中),并且更安全(发生段错误的可能性要小得多)。

关于Python:将数据从扭曲的套接字读取到 SWIG-ed 结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25210623/

相关文章:

c++ - C++ 程序员应该如何用 C 设计软件?

C#如何连接公网ip

python - 具有值历史的非同质数据的数据库设计

python - 来自不同模型的 Django 模型引用

python - 预创建多线程 Python 应用程序

c - 以下程序打印的输出是什么?如何评估if条件表达式?

python - Pandas:当大小不相等时,如何将 Python 列表中的值分配给数据框中的列

c - 用 C 编写递归函数打印 1 和 n 个零

c++ - 客户端/服务器 C++ 之间的通信问题

python - Tkinter .after 方法卡住窗口?