7

I am trying to bind python3 in C++.

When using this:

Py_SetProgramName(argv[0]);

it gives this error:

error C2664: 'Py_SetProgramName' : cannot convert parameter 1 from 'char *' to 'wchar_t *'

Even though that's how the documentation example shows to do it.

I also tried this:

Py_SetProgramName((wchar_t*)argv[0]);

But apparently that's the wrong way to do it.

So how do I fix this, and is there any other good resources on binding Python 3 in C++?

0

3 Answers 3

4

The official way of converting from char to wchar_t is now :

wchar_t *program = Py_DecodeLocale(argv[0], NULL);
Py_SetProgramName(program);

on a side note mbstowcs is not reliable on some platforms.

A quite good example of using python2/3 with c++ would be Panda3D. a c++ game engine scripted with python, that also provides a c++ module builder.

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

2 Comments

sorry but i don't see any answer for "is there any other good resources on binding Python 3 in C++", correcting wrongs like mbstowcs use is 4 months old ( python3.7+ ) and imho important for newcomers. also embedding python in C++ is not very well supported so question has no age.
not saying you cant add to it, its just funny to me that its so old
3

Try following:

wchar_t progname[FILENAME_MAX + 1];
mbstowcs(progname, argv[0], strlen(argv[0]) + 1);
Py_SetProgramName(progname);

http://www.cplusplus.com/reference/cstdlib/mbstowcs/

9 Comments

MAXPATHLEN is undefined, I hard-coded it to 255 which allows me to compile. It appears to work though just like my 'wrong' solution I have no way to test it just yet. +1
Insert #include <sys/param.h> if you are using Unix.
@Brae, I can't find MAXPATHLEN equivalent in Windows. Use #define MAXPATHLEN 1024.
@Brae, I replaced MAXPATHLEN with FILENAME_MAX. It does not require header. (not tested in Windows).
be warned mbstowcs is a real source of trouble of some platforms. One random example would be android api 19. Python3.7+ has now integrated official workarounds and unicode coercion see PEP 538/540.
|
1

I suggest you look at this question

The example documentation for the Python 3 API appears to have not been upgraded from Python 2 - the example you show is one of them (I have reported some of the others).

I have found no good documentation in this area. Even the new (Python 3) editions of well-known Python books either cover this subject sparsely or have code errors (usually because the code comes from Py2).

1 Comment

That's a pain, thanks for the link, it looks very similar to falsetru's answer.

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.