SOLVED Executing Python code in C++: crash when importing c4d package


I'm trying to do some things using Python, so I wrote a simple function to execute Python code, based on the example in the SDK docs. I've been using this function before (see with no problems.

Here is the code to execute Python code from within a C++ plugin:

maxon::Result<void> ExecutePythonCodeSimple(const maxon::String &code)

	// Check code
	if (code.IsEmpty())
		return maxon::IllegalArgumentError(MAXON_SOURCE_LOCATION);

	// Create VM ref and scope
#if API_VERSION >= 23000
	const maxon::VirtualMachineRef& vm = MAXON_CPYTHON37VM();
	const maxon::VirtualMachineRef& vm = MAXON_CPYTHON27VM();
	const maxon::VirtualMachineScopeRef scope = vm.CreateScope() iferr_return;

	// Init script
	iferr (scope.Init("Python Script"_s, code, maxon::ERRORHANDLING::PRINT, nullptr))
		const String errorMessage = "Error on Init()"_s;
		return maxon::UnknownError(MAXON_SOURCE_LOCATION, errorMessage);

	// set __name__ = __main__
	scope.Add("__name__"_s, maxon::Data("__main__"_s)) iferr_return;

	// executes the script and returns when it got executed.
	// info: if the script causes an unexpected infinite loop, Execute() does not return
	// and there is no way to stop from the outside.
	iferr (scope.Execute())
		const String errorMessage = "Error on Execute()"_s;
		return maxon::UnknownError(MAXON_SOURCE_LOCATION, errorMessage);
	return maxon::OK;

The Python code I want to execute relies on functionality from the c4d package. Here's the - very simplified - code:

maxon::Result<void> MyFunction()

	maxon::String theCode;
	theCode = "import c4d\n"_s;
	theCode += "print('Hello World!')\n"_s;

	// Execute code
	ExecutePythonCodeSimple(theCode) iferr_return;
	return maxon::OK;

So, the actual Python code comes down to this:

import c4d
print('Hello World!')

It crashes reproducibly:
Screenshot 2021-01-06 at 15.14.15.jpg

If I remove the line import c4d, it does not crash.

Why, and how can I solve this?

Thanks in advance & best greetings,

You are calling the Python module before it is loaded and initiated. You could try setting the priority of your plugin to ensure it is the last plugin loaded.

Also you shouldn’t be calling that in PluginStart. You should be calling it once all the plugins have been started, ie the Python module.

Instead try calling it on StartActivity or possibly Program_Started.

Hi Kent,

thanks! I'll try that! I was under the impression, that all "built-in" modules are registered before the plugins.
Will reply here and report if that solved it 🙂


I was in deed calling the code from within PluginStart(). Calling it from PluginMessage(C4DPL_STARTACTIVITY) fixed it. Thank you, Kent!