C# 调用C风格动态库(包含调用C++struct)

最近和其他公司对接,那边使用的是C++开发的动态库,但是我们这边需要封装成C#的动态库,研究了下,一下贴些各种接口使用,共大家参考
//C# 对等声明C++那边的结构体
[StructLayout(LayoutKind.Sequential)]
public struct AgentInfo
{
public Int32 m_callEvent;

    public Int32 m_agentStatus;

    public Int32 agentCallType;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    public char[] dstNube; //被叫号码
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    public char[] dstNickName;//被叫昵称
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    public char[] localNube; //主叫
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    public char[] localNickName;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
    public char[] sid;   //会话id
   /* public AgentInfo()
    {
        m_callEvent = CallEvent.ON_SET_BUSY_OR_READY_FAILED;
        m_agentStatus = AgentStatus.AGENTSTATUS_ALERING;
        agentCallType = new Int32();
        dstNube = new char[32];
        dstNickName = new char[32];
        localNube = new char[32];
        localNickName = new char[32];
        sid = new char[128];
    }*/
};

//指针转化成结构体
static public Object BytesToStruct(IntPtr buffer, AgentInfo obj)
{
var result = Marshal.PtrToStructure(buffer,obj.GetType());
return result;
}
//获取对象地址
static public IntPtr TextBoxtoIntPtr(TextBox obj)
{
return obj.Handle;
}
static public IntPtr PictureBoxtoIntPtr(PictureBox obj)
{
return obj.Handle;
}

//带有回调函数的式的C风格接口使用办法
[DllImport(@”ButelAgentAdapter.dll”, EntryPoint = “ButelTryInitVedio”, CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.StdCall)]
public static extern int ButelTryInitVedio(BUTELCONECTEVENTCALLBACK handleL, int nAgentType, int nTypeParam);
****C# 委托(Delegate)
C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。
委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。**
public delegate void BUTELCONECTEVENTCALLBACK(int type, IntPtr data, string msg, string szExtendSignalInfo);
public static BUTELCONECTEVENTCALLBACK callback;
private void UserLogin_Fun(int type, IntPtr data, string msg, string szExtendSignalInfo)
{
var m = CallBackInfo();
MessageBox.Show(“” + m);
if(null != data)
{
AgentInfo hh = new AgentInfo();
hh = (AgentInfo)BytesToStruct(data, hh);
}
if (m == 4)
{
ButelTryEnableCamera(true);
Form form1 = new Form();
//panel1.Controls.Add(form1);
Form form2 = new Form();
//panel2.Controls.Add(form2);
ButelSetVideoWindowrun((Int32)PictureBoxtoIntPtr(pictureBox1), (Int32)PictureBoxtoIntPtr(pictureBox2));
ButelTryLogin(“75cbefe71bd3474fa08755058261a5f9”, “45016442”, “1100112”, “80070128”);

        }
        if (m == 12)
        {
            ButelTrySetBusyrun();
        }
        if (m == 2)
        {
            ButelTryAnswer();
        }
    }

猜你喜欢

转载自blog.csdn.net/u012453032/article/details/80256983