来自C ++的C#回调提供了访问冲突

时间:2013-03-07 20:07:24

标签: c# c++ callback unmanaged

编辑(谢谢ildjarn!): 通过将委托(和回调函数签名匹配)更改为

来解决
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void InstallStatusDel([MarshalAs(UnmanagedType.LPStr)]string Mesg, int Status);

原帖:

我在使用C#编写的.net应用程序中遇到问题,该应用程序调用C dll中的函数。我看过其他类似问题的线索,但我必须错过一些不同的东西。当我在C#中调试它时,我能够在InstallStatusCallback中遇到断点但是当执行退出InstallStatusCallback时会出现AccessViolationException。我已尝试使用C进行调试,并且在执行从回调返回之前发生访问冲突。感谢您的任何意见。

C dll中的项目设置默认设置为使用__cdecl。在C DLL中,以下代码已经到位:

typedef void (__cdecl *StatusCallback)(const char* Mesg, int Status);
__declspec(dllexport) int Install(void* thing1, void* thing2, void* thing3, StatusCallback Func);


int Install(void* thing1, void* thing2, void* thing3, StatusCallback Func)
{
    Func("msg", 3);
    return 0;
}

在C#中我有:

public partial class InstallerStatus : Form
{
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void InstallStatusDel(StringBuilder Mesg, int Status);

    public static extern int Install(IntPtr thing1, IntPtr thing2, IntPtr thing3, InstallStatusDel Func);
    [DllImport("myDll.dll", CallingConvention = CallingConvention.Cdecl)]

    private IntPtr mThing1;
    private IntPtr mThing2;
    private InstallStatusDel mInstallStatusFunc;
    private BackgroundWorker mInstallWorker;

    public InstallerStatus(IntPtr pThing1, IntPtr pThing2)
    {
        InitializeComponent();

        mThing1 = pThing1;
        mThing2 = pThing2;
        mInstallStatusFunc = InstallStatusCallback;

        mProgressBar.Minimum = 0;
        mProgressBar.Maximum = 100;
        mProgressBar.Value = 0;

        mInstallWorker = new BackgroundWorker();
        mInstallWorker.DoWork += new DoWorkEventHandler(InstallWork);
        mInstallWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(InstallWork_Completed);
    }

    private void InstallWork(object sender, DoWorkEventArgs e)
    {
        Install(mThing1, mThing2, IntPtr.Zero, mInstallStatusFunc);
    }

    private void InstallWork_Completed(object sender, RunWorkerCompletedEventArgs e)
    {
        Close();
    }

    private void InstallStatusCallback(StringBuilder PartName, int Status)
    {
    }

    private void InstallLoad_Shown(object sender, EventArgs e)
    {
        mInstallWorker.RunWorkerAsync();
    }
}

1 个答案:

答案 0 :(得分:2)

通过将委托(和要匹配的回调函数签名)更改为

来解决
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void InstallStatusDel([MarshalAs(UnmanagedType.LPStr)]string Mesg, int Status);

谢谢ildjarn!