我在C#中使用P / Invoke从C ++ DLL调用本机函数,如下所示:
C ++ DLL:
extern "C"
{
// Function: Create Wmv video from sequences image. Codec: WMV3 (VC-1)
__declspec(dllexport) bool __stdcall CreateWMV(...)
{
...
}
}
C#包装器类。我创建了C#包装器类函数来映射本机C ++代码:
[DllImport("AVIEncoder.dll", EntryPoint = "CreateWMV", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool createWmv(...);
我确定参数在C#中正确编组,因为当我直接在客户端C#代码中调用时它将成功运行。仅当我将函数放在后台线程中时,才出现此问题。
private void Test()
{
....
createWmv(...); // This call was processed without issue
Thread backgroundThread = new Thread(
new ThreadStart(()=>
{
createWmv(...); // This call causes AccessViolationException
}
}
函数createWmv()使用Media Foundation接口生成Wmv视频。我尝试调试,发现当我用本机代码注释掉函数IMFSinkWriter :: WriteSample()时,程序运行而不会引起异常。
因此,我想知道Microsoft在SinkWriter实现中是否有一些怪异之处。是否有人以这种方式使用Media Foundation存在相同的问题?
按照oleksii的评论,我在下面设置:
backgroundThread.TrySetApartmentState(ApartmentState.STA); // Add this to fix createWMV() in multithreading
backgroundThread.Name = "CreateVideoThead";
backgroundThread.Start();
现在,该程序可以毫无例外地运行。感谢C#线程中ApartmentState的概念。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句