gpt4 book ai didi

c# - 在多线程应用程序中使用带有媒体基础接口(interface)的 P/Invoke 发生 AccessViolationException

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:18:04 28 4
gpt4 key购买 nike

我在 C# 中使用 P/Invoke 从 C++ DLL 调用 native 函数,如下所示:

  1. C++ 动态链接库:

        extern "C"
    {
    // Function: Create Wmv video from sequences image. Codec: WMV3 (VC-1)
    __declspec(dllexport) bool __stdcall CreateWMV(...)
    {
    ...
    }
    }
  2. C# 包装类。我创建了 C# 包装器类函数以映射到 native 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() 使用媒体基础接口(interface)生成 Wmv 视频。我尝试调试,发现当我在 native 代码中注释掉函数 IMFSinkWriter::WriteSample() 时,程序运行时不会导致异常。

因此,不知微软在SinkWriter的实现上是不是有什么奇怪的地方。有没有人以这种方式使用 Media Foundation 遇到同样的问题?

最佳答案

关注oleksii的评论,我在下面设置:

backgroundThread.TrySetApartmentState(ApartmentState.STA); // Add this to fix createWMV() in multithreading
backgroundThread.Name = "CreateVideoThead";
backgroundThread.Start();

现在,程序可以正常运行了。感谢ApartmentState的概念在 C# 线程中。

关于c# - 在多线程应用程序中使用带有媒体基础接口(interface)的 P/Invoke 发生 AccessViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30569110/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com