Unity中使用UnmanagedExports实现Python调用函数的问题求助
问题描述
我尝试在Unity项目中通过UnmanagedExports框架实现Python调用C#函数,但Python调用时出现错误:
AttributeError: function 'ConvertRawToBinData' not found
按建议切换为x64目标构建项目后,Visual Studio又出现库导入错误:
The type or namespace name 'type/namespace' could not be found
请问Unity项目能否使用UnmanagedExports?如果可以,正确的操作方式是什么?
相关代码
C#代码
using RGiesecke.DllExport; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace ConverterAPI { public class ConverterAPI { [DllExport("ConvertRawToBinData", CallingConvention = CallingConvention.StdCall)] public static void ConvertRawToBinData(string settingsPath, string collectionSettingsPath, string rawDataPath) { Settings settings = Util.ImportJson<Settings>(settingsPath); CollectionSettings CollectionSettings = Util.ImportJson<CollectionSettings>(collectionSettingsPath); Converter.Convert(settings, CollectionSettings, rawDataPath); } } }
Python代码
import ctypes import os from pathlib import Path, PurePath apiPath = PurePath(assetsPath.parent, 'Build', 'Target', 'API.dll') converterAPI = ctypes.cdll.LoadLibrary(str(apiPath)) converterAPI.ConvertRawToBinData("", "", "")
可行方案:Unity中使用UnmanagedExports的正确步骤
Unity项目可以使用UnmanagedExports,但需要严格遵循以下步骤规避架构不匹配、依赖缺失等问题:
1. 解决架构不匹配问题(Python找不到函数的核心原因)
- Python与Unity构建的DLL必须为同一架构:64位Python对应x64架构DLL,32位Python对应x86架构DLL。
- 切换x64后出现的命名空间错误,大概率是UnmanagedExports包未正确适配架构,或Unity项目引用配置有误。
2. 正确配置Unity项目与UnmanagedExports
步骤1:导入适配架构的UnmanagedExports文件
不要单独在Visual Studio安装NuGet包,直接下载对应架构的RGiesecke.DllExport.dll及MSBuild任务文件,放入Unity项目的Assets/Plugins目录下。需在Plugins内创建x86、x64子目录分别存放对应架构文件,并在Unity Inspector中设置匹配的平台架构。步骤2:调整代码与调用约定匹配
导出函数使用了StdCall调用约定,但ctypes默认是cdecl,需在Python端显式指定:import ctypes import os from pathlib import Path, PurePath apiPath = PurePath(assetsPath.parent, 'Build', 'Target', 'API.dll') converterAPI = ctypes.cdll.LoadLibrary(str(apiPath)) # 指定参数类型与返回值类型 converterAPI.ConvertRawToBinData = ctypes.WINFUNCTYPE( None, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_wchar_p )(("ConvertRawToBinData", converterAPI)) # 调用函数 converterAPI.ConvertRawToBinData("", "", "")同时,Unity中需将含导出函数的C#脚本所在Assembly设置为仅编译到Standalone平台,避免Editor编译出错。
步骤3:构建正确的DLL
在Unity Build Settings中选择对应架构(x64/x86)的Standalone平台,构建时确保含导出函数的Assembly被打包到输出目录。也可将导出函数代码放在单独的Class Library项目中,用Visual Studio编译为DLL后导入Unity,注意Class Library的.NET版本需与Unity匹配(如Unity用.NET Framework 4.x,Class Library也需对应版本)。
3. 解决命名空间/类型找不到的问题
- 检查
Assets/Plugins目录下是否存在对应架构的RGiesecke.DllExport.dll,且Inspector中已勾选正确平台。 - 若Visual Studio打开Unity项目编译出错,确认已加载Unity所有引用,且UnmanagedExports的NuGet包是针对当前架构安装的。
4. 额外注意事项
- 导出函数必须为静态函数,参数类型需与Python端兼容(如C#的
string对应Python的c_wchar_p)。 - 不要在导出函数中直接调用Unity专属API(如
GameObject、Transform),这类API依赖Unity运行时环境,单独DLL无法调用。若需触发Unity逻辑,可将导出函数作为入口,在Unity运行状态下调用。 - 建议先单独编译Class Library生成DLL,用Python测试通过后再导入Unity集成。
内容的提问来源于stack exchange,提问作者Ling

