1、托管代码向非托管代码传递字符串
非托管API:
extern "C" __declspec(dllexport)
int _cdeclWriteDataToFCSFile(char* FilePath);
托管:
[DllImport(_Business.dll, EntryPoint = "WriteDataToFCSFile", CallingConvention = CallingConvention.Cdecl)]
[DllImport(_dllName,EntryPoint ="SendCommand",CallingConvention =CallingConvention.Cdecl)]
public static extern int SendCommand( short CmdCode, short DstDeviceCode, shortSrcDeviceCode, float[] Params, int nSize);[DllImport(_dllName,EntryPoint ="GetHardDeviceInfo",CallingConvention=CallingConvention.Cdecl)]
public static extern boolGetResponse( ref shortresponseCode, out IntPtrparameters, ref intnSize);//需要将数据从非托管内存指针复制到托管字符数组,关键代码如下:
if (nSize >= 0)
{
float[] paramsArray = new float[nSize];
Marshal.Copy(parametersPtr,paramsArray, 0, nSize);
[DllImport(_dllName,EntryPoint ="GetTheArray",CallingConvention =CallingConvention.Cdecl)]
unsafe publicstaticexternint* GetTheArray(ref int nSize);
使用方法举例:
unsafe
{
int* theArrayPtr;
string arrayMember = "";
int int= 0;
theArrayPtr= BusinessCenterDLL.GetTheArray(ref nSize);
if(theArrayPtr!= null)
{
for (int i = 0; i< nSize; i++)
{
originalCommand+= theArrayPtr[i].ToString();
originalCommand+= ",";
}
}
}