Kaynağa Gözat

c++调用python脚本

Tang Hai 14 yıl önce
ebeveyn
işleme
65bc71c499

+ 5 - 0
Src/Egametang/Python/PythonInit.h

@@ -28,6 +28,11 @@ public:
 	{
 		return Py_GetVersion();
 	}
+
+	void PrintError()
+	{
+		PyErr_Print();
+	}
 };
 
 } // namespace Egametang

+ 71 - 0
Src/Egametang/Python/PythonInitTest.cc

@@ -5,6 +5,8 @@
 
 namespace Egametang {
 
+using namespace boost::python;
+
 class PythonInitTest: public testing::Test
 {
 public:
@@ -55,6 +57,75 @@ TEST_F(PythonInitTest, Dict)
 	ASSERT_EQ(2, boost::python::len(dict));
 }
 
+class Person
+{
+private:
+	int guid_;
+	std::string name_;
+
+public:
+	Person(): guid_(0)
+	{
+	}
+	void SetGuid(int guid)
+	{
+		guid_ = guid;
+	}
+
+	int Guid() const
+	{
+		return guid_;
+	}
+
+	void SetName(const std::string& name)
+	{
+		name_ = name;
+	}
+
+	std::string Name() const
+	{
+		return name_;
+	}
+};
+
+typedef boost::shared_ptr<Person> PersonPtr;
+
+BOOST_PYTHON_MODULE(Person)
+{
+	boost::python::class_<Person>("Person")
+		.def("SetGuid", &Person::SetGuid)
+		.def("Guid", &Person::Guid)
+	;
+	boost::python::register_ptr_to_python<PersonPtr>();
+}
+
+TEST_F(PythonInitTest, EnterPythonScript)
+{
+	try
+	{
+		initPerson();
+		boost::python::object main_module = boost::python::import("__main__");
+		boost::python::object main_namespace = main_module.attr("__dict__");
+		PersonPtr person(new Person);
+		main_namespace["person"] = person;
+		std::string str = "import sys\n"
+				"sys.path.append('../../../Src/Egametang/Python/')\n"
+				"import Person\n"
+				"import PythonInitTest\n"
+				"PythonInitTest.fun(person)\n";
+		ASSERT_EQ(0, person->Guid());
+
+		// 进到python脚本层设置person的值为2
+		boost::python::exec(str.c_str(), main_namespace);
+		ASSERT_EQ(2, person->Guid());
+	}
+	catch (boost::python::error_already_set& err)
+	{
+		python_init.PrintError();
+		throw err;
+	}
+}
+
 } // namespace Egametang
 
 int main(int argc, char* argv[])

+ 5 - 0
Src/Egametang/Python/PythonInitTest.py

@@ -0,0 +1,5 @@
+#!/usr/bin/python
+#-*- coding: utf-8 -*-
+
+def fun(person):
+	person.SetGuid(2)