0

I'm trying to pass a string value to a Python function and get a utf-8 string value. The function retrieves Japanese characters and returns characters in another language.

I used ctypes.windll.user32.MessageBoxW in the Python script and made sure there is no problem with the Python function. And I tried a simple function like return 'hello world' to test. I also checked every function with assert. I guess the problem starts with PyBytes_AsString. It always returns DB DB DB DB DB DB DB... (in hex). But I don't know how to fix this.

char* result;
PyObject* module, *func, *arg, *ret, *value;

Py_Initialize();

PyObject* sysPath = PySys_GetObject("path");
PyObject* path = PyUnicode_FromString(".");
PyList_Append(sysPath, path);

module = PyImport_ImportModule("test");

if (module != 0)
{
    const wchar_t* w = L"翻訳テスト";
    func = PyObject_GetAttrString(module, "translate");
    arg = PyTuple_New(1);
    value = PyUnicode_FromWideChar(w, wcslen(w));
    PyTuple_SetItem(arg, 0, value);
    ret = PyObject_CallObject(func, arg);

    PyObject* repr = PyObject_Repr(ret);
    PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
    result = PyBytes_AsString(str);

    Py_DECREF(repr);
    Py_DECREF(str);
    Py_DECREF(module);
    Py_DECREF(func);
    Py_DECREF(arg);
    Py_DECREF(ret);

    fstream file("text.txt", std::ios::out);
    file << result;
    file.close();
}

Py_Finalize();

1 Answer 1

0

result = PyBytes_AsString(str) returns a pointer to the internal buffer of str, so don't Py_DECREF(str) before you write result to the file.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I feel retarded. I wasted a day for this..... I really appreciate you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.