在C#中使用C ++结构和方法 [英] Using C++ structures and methods in C#

查看:71
本文介绍了在C#中使用C ++结构和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#中使用C ++结构和方法?提供有关C ++中不同数据类型成员的示例.

How to use C++ structures and methods in C#? Provide examples for different data type members in C++.

推荐答案


我提出了这个问题,以提供一些建议在C#中使用C ++方法的示例.

基于一个小场景的示例:我在C ++中有一个结构,这是C ++中方法的输出.我想在C#中使用此方法.
为此,我必须在C#中创建等效的结构和包装方法.该结构作为C ++的指针返回.因此,我们从C#中捕获了该指针,并将该指针编组为结构.

I raised this question to provide few examples on using C++ methods in C#.

Example based on a small Scenario: I have a structure in C++ and this is the output of a method in C++. I want to use this method in C#.
For this, I have to create a equivalent structure and wrapper method in C#. The structure returned as a pointer from C++. So, we catch that pointer from C# and marshall that pointer to structure.

enum CustomerType //C++ enum
    {
        Personal = 0,
        Corporate = 1
    };


  struct Customer //C++ structure
    {
		_TCHAR		CustomerName[50];
		_TCHAR		Address[250];
		INT32		CustomerNumber;
		CustomerType  	CustomerType;
		bool 		IsHandicapped;
	};


	//C++ method
	__declspec(dllexport) HRESULT ReadCustomer(LPCTSTR cNumber, LPVOID *pCustomer)
	{
		try
		{
			.....
			.....
			Customer* objCustomer = (Customer*)CoTaskMemAlloc(sizeof(Customer));
			......
			//Fill customer
			......
			*pCustomer = (LPVOID)(objCustomer);			
			return 0L;
		}
		catch(...)
		{
		}
	}


上述C ++结构和方法位于本机"Customer.dll"中.


The above C++ structures and methods are in native "Customer.dll"

public enum CustomerType //C# enum
   {
       Personal =  0,
       Corporate = 1
   }

   [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] //C# structure
   {
   public struct Customer
   {
       [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
       public String CustomerName;
       [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 250)]
       public String Address;
   public int CustomerNumber;
   public CustomerType  CustomerType;
   [MarshalAs(UnmanagedType.U1)]
       public bool IsHandicapped;
   }
   //Equivalent C# wrapper method

       [DllImport("Customer.dll", EntryPoint = "ReadCustomer", CallingConvention = CallingConvention.Cdecl)]
       private extern static int GetCustomerDetails([MarshalAs(UnmanagedType.LPTStr)] string cNumber
                                             , out IntPtr pCustomer);



我将实现一个使用此包装器的方法来获取客户详细信息并编组结构指针.



I will implement a method to use this wrapper to get customer details and marshal the pointer to structure.

 public Customer GetCustomerDetails(string cNumber, out bool bStatus)
{

	int result = -1;
            bStatus = false;
            IntPtr dataPtr = IntPtr.Zero;
            Customer objCustomer = new Customer();
            try
            {
                result = GetCustomerDetails(cNumber, out dataPtr);
                if (result == 0)
                {
                    objCustomer = (Customer)Marshal.PtrToStructure(dataPtr, typeof(Customer));
                    Marshal.FreeHGlobal(dataPtr);
                    bStatus = true;
                }
                else
                {
                    bStatus = false;
                }
            }
            catch (Exception ex)
            {
                Marshal.FreeHGlobal(dataPtr);
            }
            return objCustomer;
}



C ++和等效的C#方法的另一个示例.

EntryManager.dll包含以下方法:



Another example of C++ and equivalent C# method.

EntryManager.dll contains the below method:

__declspec(dllimport) LONG WINAPI CreateEntry(LPTSTR EntryLocation, LPTSTR EntryName,  TCHAR** Belongings,  LONG BelongingsSize)//Belongings=Array of items related to Entry



上面的等效C#方法是:



Equivalent C# method for the above is:

 [DllImport("EntryManager.dll", EntryPoint = "CreateEntry", CharSet = CharSet.Unicode)]
        static extern int CreateEntry(
            [MarshalAs(UnmanagedType.LPWStr)]string EntryLocation,
            [MarshalAs(UnmanagedType.LPWStr)]string EntryName,
           [MarshalAsAttribute(UnmanagedType.LPArray,
              ArraySubType = UnmanagedType.LPWStr)] string[] Belongings, int BelongingsSize);
//In C++, we can not find the size of array dynamically as we do in C#(like objArray.Length). So, we need to send the size of array.




关于通知的另一个示例:当数据更改时,使用C ++中的回调机制完成通知.我想在C#中使用相同的机制.当数据更改时,该通知应调用C#回调方法.




A different example on notification: When the data changed, notification done using callback mechanism in C++. I want to use the same mechanism in C#. When data changed, that notification should call C# callback method.

//In C++ "EntryManager.dll"
typedef void (__stdcall *CBNotifyFunc)(LPTSTR);

DWORD WINAPI ChangeNotify(LPTSTR TargetLocation, int SearchScope, LPTSTR SearchFilter, CBNotify callBackFunction)







//In C#
   public delegate void CBNotify([MarshalAs(UnmanagedType.LPTStr)]string TargetLocation);

        [DllImport("EntryManager.dll", EntryPoint = "ChangeNotify", CallingConvention = CallingConvention.Winapi)]
        public static extern UInt32 GetChangeNotifications([MarshalAs(UnmanagedType.LPWStr)]string TargetLocation,
       int SearchScope,  [MarshalAs(UnmanagedType.LPWStr)]string SearchFilter,
        [In, MarshalAs(UnmanagedType.FunctionPtr)]CBNotify callBackFunction);

        public void FunctionCall(string name)
        {
            MessageBox.Show("dfd  : " + name);
        }
//Using the above method GetChangeNotifications

uint fsdf = GetChangeNotifications("EntryLocation1", 1, null, FunctionCall); //This registers the Call back method. Whenever there is change, it calls FunctionCalll method.



我提供了非常基本的信息和代码来使用C#中的C ++方法和结构,足以理解该主题.



I have provided the very basic information and code to use C++ methods and structures in C# which is enough to understand this topic.


这篇关于在C#中使用C ++结构和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆