我在 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/