我在C++中使用aio_write创建了一个非常简单的函数。在参数中,我得到了创建文件及其大小的路径。要创建新文件,我使用int open(const char *pathname, int flags, mode_t mode)
。const char *参数只给出第一个字符(在python3上)
然后我使用: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
这是蟒蛇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接受了Unicode跳跃,所以前两个'char'是第一个字符,第二个'char'是零。 – molbdnilo