ctypes,输出格式函数c有问题++

2024-09-28 22:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个ctype函数,它调用一个连接到套接字的C++库,并向它发送一个5字节的十六进制数据包。函数connects以正确的方式发送十六进制代码I write I input The peripheral responses(I checked with Wireshark),但是带有ctype的python代码无法很好地互操作它作为响应接收的数据包(总是5字节)。有人能给我一些建议吗?我错在哪里?随函附上C++代码、python代码和函数的答案

我已经尝试过c\u char\p、ctypes.POINTER(LP\u c\u char)、ctypes.POINTER(LP\u c\u char),但是没有任何结果函数的返回值总是0

C++代码连接

#include <stdio.h>
#include <errno.h>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <iostream>
#include <unistd.h>
#include <sstream>

extern "C" char * connect_pe_func(int argc, char *argv[])
{
   int sockfd, n;
   int connected = 0;
   struct sockaddr_in servaddr;
   std::string serveraddr = argv[0];

   sockfd = socket(AF_INET, SOCK_STREAM, 0);

   bzero(&servaddr, sizeof(servaddr));
   servaddr.sin_family = AF_INET;
   servaddr.sin_addr.s_addr = inet_addr(serveraddr.c_str());
   servaddr.sin_port = htons(9761);

   connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

   std::string pref_hex;
   std::string hex("0x");
   std::string test = argv[1];
   size_t numbytes = test.size() / 2;
   uint8_t command[numbytes];

   for (size_t w = 0, x = 0; w < numbytes; ++w, x += 2)
   {
      pref_hex = hex + test.substr(x, 2);
      //cout << pref_hex;
      command[w] = stoi(pref_hex, nullptr, 16);
   }

   int bytes_to_send = sizeof(command);

   send(sockfd, command, bytes_to_send, 0);
   uint8_t output_command[numbytes];
   recv(sockfd, output_command, bytes_to_send, 0);
   close(sockfd);
   char test_out[10];

   for (size_t w = 0, x = 0; w < numbytes; ++w, x += 2)
   {
      test_out[x] = (char)output_command[w];
   }
   return test_out;

}

python代码

import sys
import ctypes

lib = ctypes.CDLL('./connect_pe_func.so')

LP_c_char = ctypes.POINTER(ctypes.c_char)
LP_LP_c_char = ctypes.POINTER(LP_c_char)

lib.connect_pe_func.argtypes = (ctypes.c_int, LP_LP_c_char)
lib.connect_pe_func.restypes = ctypes.c_char_p
argv = ["192.168.2.170","2600000026"]
argc = len(argv)

p = (LP_c_char*len(argv))()
for i, arg in enumerate(argv):  # not sys.argv, but argv!!!
  enc_arg = arg.encode('utf-8')
  p[i] = ctypes.create_string_buffer(enc_arg)

na = ctypes.cast(p, LP_LP_c_char)

lib.connect_pe_func(argc, na)

我期望python代码的输出像26810000a7,但实际输出总是0


Tags: 代码teststringincludeconnectctypescommandfunc