[C++-sig] Re: Tedious Newbie Question

David Abrahams dave at boost-consulting.com
Mon Jun 7 22:32:13 CEST 2004


Gareth Simpson <g.simpson at zoo-tech.com> writes:

> Apologies in advance if this is not the list to be asking these sort of
> things.

This is exactly the right list.

> I am trying to use Boost.Python to embed a Python library into my C++
> application.  The library in question uses unicode strings internally and I
> can't for the life of me work out how to get them out and into my C++.
> Google is largely silent on the matter.
>
> The below code snippet shows what I'm trying to do.
>
> I have no problem using extract<> to get a python string into a std::string
> but trying the same thing with unicode python strings and std::wstrings
> throws an exception.
>
> Clearly I'm going about it the wrong way - what should I be doing?

Probably you need to be using a newer version of Boost; we've
supported wstring conversions since Boost 1.31.0.

But we don't support Py_Finalize(); see
http://www.boost.org/libs/python/todo.html#pyfinalize-safety


> Thanks in advance
>
> Gareth
>
>
>
>
>
> #include "stdafx.h"
>
> #include "boost/python.hpp"
>
> int _tmain(int argc, _TCHAR* argv[])
> {
> 	using namespace boost::python;
> 	Py_Initialize();
>
> 	object mainModule (borrowed(PyImport_AddModule("__main__")));
> 	object mainNamespace = mainModule.attr("__dict__");
>
> 	handle<>(PyRun_String( 
> 		"str1 = 'a string'\n"	// a simple string
> 		"str2 = u'a unicode string'\n", // a unicode string
> 		Py_file_input , mainNamespace.ptr(), mainNamespace.ptr() ));
>
> 	std::string str1  = extract<std::string>(mainNamespace["str1"]); //
> this works fine
> 	std::wstring str2  = extract<std::wstring>(mainNamespace["str2"]);
> // boom!
>
> 	Py_Finalize();
>
> 	return 0;
> }

-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com





More information about the Cplusplus-sig mailing list