Sign in to follow this  
MrDoomMaster

Unity Embedding Python into C++ Game

Recommended Posts

Hi, I've done a LOT of google research in an attempt to figure out exactly how to embed Python into my C++ application via Boost.Python. While I have succeeded somewhat in this task, there are still many unanswered questions I have. I also would like a sort of "community code review" of what I have so far to make sure that I am logically setting things up correctly. As of right now, I can successfully execute a PY script file and call a function from my embedded module, named "Script". Below is the C++ source code for the embedded part:
#define BOOST_PYTHON_DEF( func ) boost::python::def( #func, func )


using namespace boost::python;

char const* PrintHelloWorld()
{
	return "Hello World!";
}

BOOST_PYTHON_MODULE(Script)
{
	BOOST_PYTHON_DEF( PrintHelloWorld );
}

void BeginPythonTest()
{
	try
	{
		if( PyImport_AppendInittab( "Script", initScript ) == -1 )
		{
			assert( 0 );
		}

		Py_Initialize();

		object mainModule = import( "__main__" );
		object dictionary = mainModule.attr( "__dict__" );

		exec_file( "pythontest.py", dictionary, dictionary );
	}

	catch( error_already_set const& err )
	{
		PyErr_Print();
	}
}

Right now to use anything in my "Script" module, I have to explicitly import it via Python. I would like C++ to import this for me, however I haven't been able to figure out how to automate this task. Below is my Python script (very simple):
import Script
print Script.PrintHelloWorld()

So, for starters, my first question is: How can I import the "Script" module from C++ so that I will have access to it from any python scripts run from my embedded Python interpreter? Thanks in advance.

Share this post


Link to post
Share on other sites
I would rewrite your function like so:

class PyInitializer {
public:
PyInitializer() { Py_Initialize(); }
~PyInitializer() { Py_Finalize(); }
private:
PyInitializer(const PyInitializer &);
PyInitializer & operator=(const PyInitializer &);
};

int BeginPythonTest(void) {
PyInitializer py;
try {
initScript();

object main_mod = import("__main__");
object main_namespace = main_mod.attr("__dict__");
object script_mod = import("Script");
main_namespace["Script"] = script_mod;
exec_file("pythontest.py", main_namespace, main_namespace);

} catch(error_already_set) {
PyErr_Print();
throw;
}

With that you'd be able to use just

print Script.PrintHelloWorld()

as your Python script.

Share this post


Link to post
Share on other sites
Thanks SiCrane.

With your help, I have come up with the following, which works perfectly:

#define BOOST_PYTHON_DEF( func ) boost::python::def( #func, func )

using namespace boost::python;

static char const* PrintHelloWorld()
{
return "Hello World!";
}

BOOST_PYTHON_MODULE(Script)
{
BOOST_PYTHON_DEF( PrintHelloWorld );
}

void BeginPythonTest()
{
try
{
Py_Initialize();

initScript();

object main = import( "__main__" );
object mainNamespace = main.attr( "__dict__" );

mainNamespace["Script"] = import( "Script" );

exec_file( "pythontest.py", mainNamespace, mainNamespace );

Py_Finalize();
}

catch( error_already_set const& err )
{
PyErr_Print();
}

catch( std::invalid_argument const& err )
{
PyErr_Print();
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628294
    • Total Posts
      2981876
  • Similar Content

    • By CpawsMusic
      Hey there! My name is Cpaws and I compose music, sound effects and overall sound design for video games and film. I'm looking to work on a horror game mainly for fun and as an addition to my portfolio. I've used Unity & Wwise before for audio implementation.
      If you're interested in working together, don't hesitate to contact me at cpawsmusic@gmail.com
      Here's a few demo reels of my past projects: 
      Here's some snippets of some quick game music I've composed: https://soundcloud.com/cpawsmusic/sets/cpaws-video-game-film-music
      Here's my portfolio/website: https://CpawsMusic.com/
      E-mail: cpawsmusic@gmail.com
    • By muhamad rabee
      My first mobile game made by unity

      iphone: https://itunes.apple.com/us/app/aa-countdown/id1314223584?ls=1&mt=8

      android: https://play.google.com/store/apps/details?id=com.mr.AACountDown

      I appreciate every suggestion
    • By Simplepg
      https://play.google.com/store/apps/details?id=simple.gplay.GamesInABox
    • By Simplepg
      https://play.google.com/store/apps/details?id=simple.gplay.GamesInABox
    • By ForgedInteractive


      Who We Are
      We are Forged Interactive, a small team of like-minded game developers with the sole purpose of making games we love! We're a team of artists, animators, programmers, level designers, writers, composers, producers, and other creative minds. We want to make games that you, the modern gamer want to play! We hope to build a community that enjoys our games as much as we love creating them. With your feedback and support we will be able to achieve that.

      About the Game
      GAME NAME is a fun, action-packed army builder with unique characters, challenges and engaging levels. Set forth on an adventure to protect friends, family and countrymen from new adversaries. Once defeated your enemies turn coat and join you in your adventures. Players can enjoy a range of troops and abilities based on their gameplay style which become more important as maps introduce more challenging terrain, enemies and bosses. Strong orc knights, dangerous shamans, and even a dragon are out on the prowl. Knowing when to fight and when to run, and how to manage your army is essential. Your actions alone decide the fate of this world.

      Previous Work by Team
      Although we are working towards our first game as a team, our team members themselves have past experience in the industry.
      This includes members who have worked on titles including:
      Final Fantasy Kingsglaive, FIFA, Xcom 2 and Civilization.

      Who are we looking for? 3D Modellers Concept Artists Marketing Specialists Level Designer

      What do we expect? Reference work or portfolio. Examples what have you already done and what projects you have worked on academic or otherwise. The ability to commit to the project on a regular basis. If you are going on a two-week trip, we don't mind, but it would be good if you could commit 10+ hours to the project each week. Willingness to work with a royalty based compensation model, you will be paid when the game launches. Openness to learning new tools and techniques
      What can we offer? Continuous support and availability from our side. You have the ability to give design input, and creative say in the development of the game. Shown in credits on websites, in-game and more. Insight and contacts from within the Industry.
      Contact
      If you are interested in knowing more or joining. Please email or PM us on Skype. Myself or Colin will reply to you within 48 hours.

      E-mail: Recruitment@ForgedInteractive.com
      Skype: ForgedInteractive

      Regards,
      David and Colin

      Follow us on:

      Facebook: https://www.facebook.com/ForgedInteractive/
      Twitter: @ForgedInteract
      Youtube: https://www.youtube.com/channel/UCpK..._as=subscriber
      Reddit: https://www.reddit.com/user/Forged_Interactive/
  • Popular Now