更新 - 我写了一个更通用的例子(加上一个包含整个 VS2008 项目的 zip 文件的链接)作为我博客上的条目here.
抱歉,我来得太晚了,但这是我将 IronPython 集成到 Visual Studio 2008 - .net 3.5 中的 C++/cli 应用程序中的方法。 (实际上是 C/C++ 的混合模式应用)
我为一个用 Assembly 编写的地图制作应用程序编写插件。该 API 已公开,以便可以编写 C/C++ 附加组件。我将 C/C++ 与 C++/cli 混合使用。此示例中的一些元素来自 API(例如 XPCALL 和 CmdEnd() - 请忽略它们)
///////////////////////////////////////////////////////////////////////
void XPCALL PythonCmd2(int Result, int Result1, int Result2)
{
if(Result==X_OK)
{
try
{
String^ filename = gcnew String(txtFileName);
String^ path = Assembly::GetExecutingAssembly()->Location;
ScriptEngine^ engine = Python::CreateEngine();
ScriptScope^ scope = engine->CreateScope();
ScriptSource^ source = engine->CreateScriptSourceFromFile(String::Concat(Path::GetDirectoryName(path), "\\scripts\\", filename + ".py"));
scope->SetVariable("DrawingList", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingList::typeid));
scope->SetVariable("DrawingElement", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingElement::typeid));
scope->SetVariable("DrawingPath", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingPath::typeid));
scope->SetVariable("Node", DynamicHelpers::GetPythonTypeFromType(AddIn::Node::typeid));
source->Execute(scope);
}
catch(Exception ^e)
{
Console::WriteLine(e->ToString());
CmdEnd();
}
}
else
{
CmdEnd();
}
}
///////////////////////////////////////////////////////////////////////////////
如您所见,我向 IronPython 公开了一些对象(DrawingList、DrawingElement、DrawingPath 和 Node)。这些对象是我创建的用于向 IronPython 公开“事物”的 C++/cli 对象。
当调用 C++/cli source->Execute(scope) 行时,只有 python 行
要运行的是 DrawingList.RequestData。
RequestData 接受委托和数据类型。
当 C++/cli 代码完成后,它会调用指向
函数“钻石”
在函数 diamond 中,它通过调用来检索请求的数据
DrawingList.RequestedValue() 调用 DrawingList.AddElement(dp) 添加
应用程序可视化数据库的新元素。
最后,对 DrawingList.EndCommand() 的调用告诉 FastCAD 引擎
清理并结束插件的运行。
import clr
def diamond(Result1, Result2, Result3):
if(Result1 == 0):
dp = DrawingPath()
dp.drawingStuff.EntityColor = 2
dp.drawingStuff.SecondEntityColor = 2
n = DrawingList.RequestedValue()
dp.Nodes.Add(Node(n.X-50,n.Y+25))
dp.Nodes.Add(Node(n.X-25,n.Y+50))
dp.Nodes.Add(Node(n.X+25,n.Y+50))
dp.Nodes.Add(Node(n.X+50,n.Y+25))
dp.Nodes.Add(Node(n.X,n.Y-40))
DrawingList.AddElement(dp)
DrawingList.EndCommand()
DrawingList.RequestData(diamond, DrawingList.RequestType.PointType)
我希望这就是你要找的。p>