【问题标题】:Const char* argument gives only first character (on python3)Const char* 参数仅给出第一个字符(在 python3 上)
【发布时间】:2017-08-16 13:10:56
【问题描述】:

我在 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 对 Unicode 造成了冲击,所以前两个 chars 是第一个字符,第二个 char 是零。

标签: python c++ posix aio


【解决方案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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 2014-04-16
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    相关资源
    最近更新 更多