python - Const char* 参数只给出第一个字符(在 python3 上)

标签 python c++ posix aio

我在 C++ 中创建了一个使用 aio_write 的非常简单的函数。在参数中,我得到了创建文件的路径及其大小。要创建新文件,我使用 int open(const char *pathname, int flags, mode_t mode)

然后我使用以下代码将其编译为共享对象:g++ -Wall -g -Werror aio_calls.cpp -shared -o aio_calls.so -fPIC -lrt

在 python 2.7.5 上一切正常,但在 python 3.4 上我只得到路径的第一个字符。知道如何让它发挥作用,让它走完整条路吗?

函数代码如下:

#include <sys/types.h>
#include <aio.h>
#include <fcntl.h>
#include <errno.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <fstream>
#include "aio_calls.h"
#define DLLEXPORT extern "C"

using namespace std;

DLLEXPORT int awrite(const char *path, int size)
{
    // create the file
    cout << path << endl;
    int file = open(path, O_WRONLY | O_CREAT, 0644);

    if (file == -1)
        return errno;

    // create the buffer
    char* buffer = new char[size];

    // create the control block structure
    aiocb cb;
    memset(buffer, 'a', size);
    memset(&cb, 0, sizeof(aiocb));
    cb.aio_nbytes = size;
    cb.aio_fildes = file;
    cb.aio_offset = 0;
    cb.aio_buf = buffer;

    // write!
    if (aio_write(&cb) == -1)
    {
        close(file);
        return errno;
    }

    // wait until the request has finished
    while(aio_error(&cb) == EINPROGRESS);

    // return final status for aio request
    int ret = aio_return(&cb);
    if (ret == -1)
        return errno;

    // now clean up
    delete[] buffer;
    close(file);

    return 0;
}

如您所见,我在函数的开头写了 cout。这是在 python 2 上发生的事情:

Python 2.7.5 (default, Nov  6 2016, 00:28:07) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import cdll
>>> m=cdll.LoadLibrary('/home/administrator/Documents/aio_calls.so')
>>> m.awrite('aa.txt', 40)
aa.txt
0

这就是 python 3 上发生的事情:

Python 3.4.5 (default, May 29 2017, 15:17:55) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import cdll
>>> m=cdll.LoadLibrary('/home/administrator/Documents/aio_calls.so')
>>> m.awrite('aa.txt', 40)
a
0

最佳答案

你是对的。它与 python 3.x 中的编码和解码字符串有关。我用谷歌搜索,这个网站帮我弄明白了:http://pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/

我像这样将字符串转换为字节:

>>> filename=bytes('aa.txt', 'utf-8') 

现在我的函数也适用于 python 3。

>>> m.awrite(filename, 40) 
aa.txt 
0 

非常感谢@molbdnilo!

关于python - Const char* 参数只给出第一个字符(在 python3 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45714520/

相关文章:

python - 在 Pandas 中选择日期的任意子集

python - 使用python登录quora

c++ - 在 Visual Studio 2012 控制台应用程序中创建一个窗口?

c++ - 静态的入栈、出栈、查看、遍历栈元素

c++ - WM_KEYDOWN - 捕获导致事件的按键

sockets - 在哪里放置 Unix 域 (AF_UNIX) 套接字的端点(文件)?

c - 消息队列 - 多个进程在 msgqueue 上发送 cmd

c - 为什么 drand48() 和 friend 过时了?

python - 在这种情况下,一个 for 循环是否意味着 n 的时间复杂度?

python - Python "os.environ.get"能否返回非字符串?