最近用c#写一个小软件,要调用VC写的dll,传递参数给dll,由于是非托管代码,所以调用起来有点麻烦,要把参数转换成非托管代码的指针参数,然后再传递给dll
- using System.Runtime.InteropServices;
-
-
class CGicomIndex
- {
-
[DllImport("Index_dll.dll")]
-
unsafe private static extern Int32 create_index_file(IntPtr filename, IntPtr fieldname, UInt32 tongshu, IntPtr err);
-
-
- #region " bool CreateIndexFile( string m_strFileName, string m_strFieldName, UInt32 m_key, ref string strErr ) 对DBF文件按照指定的字段创建索引"
-
-
-
-
-
-
-
-
-
public static bool CreateIndexFile( string m_strFileName, string m_strFieldName, UInt32 m_key, ref string strErr )
- {
-
try
- {
- IntPtr ptrFileName, ptrFieldName, ptrErr;
-
-
- ptrFileName = mallocIntptr(m_strFileName);
- ptrFieldName = mallocIntptr(m_strFieldName);
- ptrErr = mallocIntptr(300);
-
-
-
if (create_index_file(ptrFileName, ptrFieldName, m_key, ptrErr) != 1)
- {
- strErr = Marshal.PtrToStringAnsi(ptrErr);
- Marshal.FreeHGlobal(ptrFileName);
- Marshal.FreeHGlobal(ptrFieldName);
- Marshal.FreeHGlobal(ptrErr);
-
return false;
- }
- Marshal.FreeHGlobal(ptrFileName);
- Marshal.FreeHGlobal(ptrFieldName);
- Marshal.FreeHGlobal(ptrErr);
-
return true;
- }
-
catch (System.Exception ex)
- {
- strErr = ex.Message;
-
return false;
- }
-
}
- #endregion
-
- #region " IntPtr mallocIntptr( string strData ) 根据数据的长度申请非托管空间"
-
-
-
-
-
-
private static IntPtr mallocIntptr( string strData )
- {
-
- Byte[] btData = System.Text.Encoding.Default.GetBytes(strData);
-
-
- IntPtr m_ptr = Marshal.AllocHGlobal(btData.Length);
-
-
-
Byte[] btZero = new Byte[btData .Length+ 1];
- Marshal.Copy(btZero, 0, m_ptr, btZero.Length);
-
-
- Marshal.Copy(btData, 0, m_ptr, btData.Length);
-
-
return m_ptr;
- }
-
-
-
-
-
-
-
private static IntPtr mallocIntptr( int length )
- {
-
- IntPtr m_ptr = Marshal.AllocHGlobal(length);
-
-
-
Byte[] btZero = new Byte[length + 1];
- Marshal.Copy(btZero, 0, m_ptr, btZero.Length);
-
-
- Marshal.Copy(btZero, 0, m_ptr, length);
-
-
return m_ptr;
-
}
- #endregion
- }
|
请发表评论