Python — Const char * аргумент дает только первый символ (на python3)

Я создал очень простую функцию в 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

1

Решение

Вы правы. Это было связано с кодированием и декодированием строк в 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!

0

Другие решения

Других решений пока нет …