c#调用C++dll 返回值为结构体,其中包含string, 报错

c++

 struct ClientInfo
{
    char adress[4];
};

extern "C" __declspec(dllexport) ClientInfo Test()
{
    ClientInfo c;
    strcpy_s(c.adress, "1234");
    return c;
}

c#

   [DllImport("ManagerAPI.dll")]
   public static extern ClientInfo Test();


      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct ClientInfo
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst =4)]
        public string address;
    }


             ClientInfo c =Test();
       Console.WriteLine(c.address);

调用的时候老是报
方法类型签名与pinvoke不兼容

c++ 中的char[] 到底对应着c#中的什么类型。 求助

2个回答

strcpy_s(c.adress, "1234");
return c;
这代码有两个问题,一个是你的c是定义在堆栈上的,怎么能用它返回呢?另一个,你的char只有4个元素,是不够复制1234的,还有\0

string需要转换一下,MarshalAs(UnmanagedType.LPStr)]string,参考这个写https://blog.csdn.net/qq385105501/article/details/82253725

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
C#调用DLL(结构体中包含回调函数)
C# 中调用dll的回调函数,该回调函数是在结构体中,rn但是c#中调用产生crash了..感觉是因为调用约定的问题.vc默认是Cdecl,而.net的delegate 是使用stdcall.请问如果才能正常调用.rnextern "C" __declspec( dllexport ) BOOL __stdcall Test(FILEWRITE* pFile)rnrn CFileWrite* pStreamWrite = NULL;rn pStreamWrite = new CFileWrite;rn pStreamWrite->Init( pFile );rn while (1)rn rn pStreamWrite->WriteBlock("1",1);rn rn return TRUE;rnrnrnrnrn//以下是该结构体说明.rnstruct FILEWRITErnrn int (*WriteBlock)(FILEWRITE* pThis, const void* buf, unsigned long size);rn;rnrnclass CFileWriternrnpublic:rn void Init(FILEWRITE * pFileWriteStruct);rn virtual BOOL WriteBlock(const void* pData, DWORD size);rnprotected:rn FILEWRITE* m_pFileWriteStruct;rnprivate:rn;rnrnvoid CFileWrite::Init(FILEWRITE * pFileWriteStruct)rnrn m_pFileWriteStruct = pFileWriteStruct;rn rnrnBOOL CFileWrite::WriteBlock(const void* pData, DWORD size)rnrn m_pFileWriteStruct->WriteBlock(m_pFileWriteStruct,pData,size);rn return TRUE;rnrnrnrnrnrn.net 中调用rn [DllImport("DLLTest2.dll",CallingConvention = CallingConvention.StdCall)]rn public static extern string Test(ref FPDF_FILEWRITE pFilewriter);rnrn public delegate int WriteBlock(ref FPDF_FILEWRITE pThis, byte[] pData, long size);rnrn public struct FPDF_FILEWRITErn rn public WriteBlock wb;rn rnrn public static int MyDelegateFunc(ref FPDF_FILEWRITE pThis, byte[] pData, long size)rn rn return 1;rn rnrn private void button1_Click(object sender, EventArgs e)rn rn FPDF_FILEWRITE pFile = new FPDF_FILEWRITE();rn pFile.wb = new WriteBlock(MyDelegateFunc);rn Test(ref pFile);rn rnrn
JNI c调用Java 返回值为String
Java定义: public String getSignatureInfo() { try { PackageInfo packageInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), PackageManager.GET_SIGNATUR
c如何调用返回值为String的java函数
java类中定义了一个静态函数,rnpublic static String getData(String id);rn我要在C中通过jni调用它。应该如何调用?rnrn我使用了rn(*env)->CallStaticStringMethod(env, MyClass, getData, id);rn但是编译的时候提示'const struct JNINativeInterface' has no member named 'CallStaticStringMethod'。rn请大家帮帮忙解答一下,谢谢。
c# 调用c++ dll 返回值为数组指针
如果c++dll的函数返回值为 数组指针,c#这边我需要怎么定义函数,怎么接收呢?rnc++:_declspec (dllexport) float* WINAPI shuju(float pv1[],float pv2[],float pv3[],float pv4[])
C#调用C++dll,返回值为结构体,结构体值转换不对
C++dll的方法为 LPECWATCHDATA WINAPI ecwGetExternsionData(WORD widx);rnLPECWATCHDATA是这样定义的 rntypedef struct rn WORD nState; //状态rn WORD nIdx; //索引rn WORD wDataCnt; //数据(lpData)项数rn char szTime[20]; //时间rn unsigned char* lpIDString; //设备号码rn unsigned char* lpNameString; //设备/用户名称rn LPCTSTR lpData[8];rnECWATCHDATA,*LPECWATCHDATA; rnrn我在C#里是这样转的 ECWATCHDATAeds = (ECWATCHDATA)(Marshal.PtrToStructure(ecwGetExternsionData(i), typeof(ExteECWATCHDATA))); ExternsionDataStruct是我自己定义的一个结构体,结构体为rn [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]rn public struct ECWATCHDATArn rnrn /// WORD->unsigned shortrn public ushort nState;rnrn /// WORD->unsigned shortrn public ushort nIdx;rnrn /// WORD->unsigned shortrn public ushort wDataCnt;rnrn /// char[20]rn [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 20)]rn public string szTime;rnrn /// char*rn public IntPtr lpIDString;rnrn /// char*rn public IntPtr lpNameString;rnrn /// char*[8]rn [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 8, ArraySubType = System.Runtime.InteropServices.UnmanagedType.SysUInt)]rn public System.IntPtr[] lpData;rn rn ECWATCHDATAeds = (ECWATCHDATA)(Marshal.PtrToStructure(ecwGetExternsionData(i), typeof(ECWATCHDATA))); 转化C#的结构体后里面有的值不对。像lpIDString,lpNameString和实际值对不上,这是什么原因?
PB调用外部dll,参数为结构体,调用报错。
外部dll最后一个参数为结构体,定义如下:rntypedef struct TagData_structrndouble value; //返回点的数值rnlong time; //返回点的时间,秒rnint status; //返回点的状态rnTagData;rn在pb中声明函数如下:Function int GetHistoryDataByTime(ref string tagname,long bytime,ref TagData tag) Library "***.dll"rnpb中声明的结构体与dll中相同rn调用时报错:Error: Specified argument type differs from required argument type at runtime in DLL function rn请教大家该如何解决?论坛搜了许多,也没有查到相关解决办法。
C#调用DLL报错
我用C#调用一个c++写的dll,通过注册dll,添加引用成功后rn在程序里写:rnHsCommX.IComm x=new HsCommX.CommClass(); rnConsole.WriteLine(x.ConnectX(1,"127.0.0.1",8000,0,"",0).ToString()) ; rn报错为:rnAccess violation at address 0614DB6C in module 'hscommx.dll'. Write of address 00000004rnrn是调用方法不对吗?请赐教。
C#调用C/C++ DLL 结构体嵌结构体集合问题
我现在有一个结构体rn[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]rnpublic struct stArnrnpubilc Int32 field1;rnpublic Byte field2;rn[MarshalAs(UnmanagedType.Struct)]rnpublic stA1 a1;rn??????????????????????????????????------集合 这里应该如何描述 这样写报错了:[MarshalAs(UnmanagedType.Struct, SizeConst = 320)]rnpubilc stA2[] s2List;rnrnrn[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]rnpublic struct stA1rnrn....................rnrnrn[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]rnpublic struct stA2rnrn....................rn
c#调用C DLL报错,救助!
[code=c]// 下列 ifdef 块是创建使从 DLL 导出更简单的rn// 宏的标准方法。此 DLL 中的所有文件都是用命令行上定义的 DYNAMICPWDCREATOR_EXPORTSrn// 符号编译的。在使用此 DLL 的rn// 任何其他项目上不应定义此符号。这样,源文件中包含此文件的任何其他项目都会将rn// DYNAMICPWDCREATOR_API 函数视为是从 DLL 导入的,而此 DLL 则将用此宏定义的rn// 符号视为是被导出的。rn#ifdef DYNAMICPWDCREATOR_EXPORTSrn#define DYNAMICPWDCREATOR_API __declspec(dllexport)rn#elsern#define DYNAMICPWDCREATOR_API __declspec(dllimport)rn#endifrnrnDYNAMICPWDCREATOR_API bool CheckPwd(char* szPwd);rnDYNAMICPWDCREATOR_API char* GetPwd();rn[/code]rnrn我做的C#代码rnrn[code=csharp] [DllImport("DynamicPwdCreator.dll")]rn public extern static string GetPwd();rn public Form1()rn rn InitializeComponent();rn rnrn private void button1_Click(object sender, EventArgs e)rn rn label1.Text = GetPwd();rn rn[/code]rnrn运行时出现rn尝试读取或写入受保护的内存。这通常指示其他内存已损坏rnrn不知道哪里有问题,请指点
c#调用包含结构体嵌套的C++ dll函数
在痛苦了两天后,终于搞定了。主要是中文乱码问题,最后受C#调用C/C++DLL收取中文字符处理这篇文章的启发,才弄好。核心思想:c++中的char是一个字节,wchar 是两个字节,c#中的char是两个字节。 ====================== C++代码========================== 里面出现的TCHAR为: typedef wchar_t WCHAR; typ...
C#调用包含结构体变量函数的vc++的dll出现问题
dll函数原型:rnrn结构体声明rntypedef struct tagIDCardDatarnchar Name[32]; //姓名rnchar Sex[4]; //性别rnchar Nation[6]; //名族rnchar Born[18]; //出生日期rnchar Address[72]; //住址rnchar IDCardNo[38]; //身份证号rnchar GrantDept[32]; //发证机关rnchar UserLifeBegin[18]; //有效开始日期rnchar UserLifeEnd[18]; //有效截止日期rnchar reserved[38]; //保留rnchar PhotoFileName[255]; //照片路径rnIDCardData;rnrn函数声明:rnSyn_ReadMsg(int iPortID,int iIfOpen,IDCardData *pIDCardData);rn说明: 读取证/卡信息rn参数:iPort [in] 整数,表示端口号。参见7.1。rniIfOpen [in] 整数,参见7.2。rnpIDCardData [out] IDCardData类型读出的数据rnrn在C#中的结构体声明如下rnpublic struct CardDatarn rn public byte[] Name;rn public byte[] Sex;rn public byte[] Nation;rn public byte[] Born;rn public byte[] Address;rn public byte[] IDCardNo;rn public byte[] GrantDept;rn public byte[] UserLifeBegin;rn public byte[] UserLifeEnd;rn public byte[] reserved;rn public byte[] PhotoFileName;rn ;rn调用:rn CardData tCardData = new CardData();rn tCardData.Name = new byte[32];rn tCardData.Sex = new byte[4];rn tCardData.Nation = new byte[6];rn tCardData.Born = new byte[18];rn tCardData.Address = new byte[72];rn tCardData.IDCardNo = new byte[38];rn tCardData.GrantDept = new byte[32];rn tCardData.UserLifeBegin = new byte[18];rn tCardData.UserLifeEnd = new byte[18];rn tCardData.reserved = new byte[38];rn tCardData.PhotoFileName = new byte[255];rnrn int i = -1;rn i = Syn_ReadMsg(iPortID, iIfOpen, out tCardData);rn报错:Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
非托管dll引用,函数结构体调用报错
int read (int nDevHandle, const OpParam *pReaderParam, DealReport *func)rntypedef structrn rn unionrn ReadParam tReadParam;rn WriteParam tWriteParam;rn op;rn unsigned int a;rn unsigned short b;rn unsigned short c;rnOpParamElement;rn以上代码如何转化成c#的结构体???急急
c#调用C的DLL
c#调用C的DLL
c#调用c的dll
小弟目前遇到一个问题,本人的程序是c#开发的,需要调用别人使用c开发的dll,而这dll里面存在一些汇编代码,在我的程序调用到存在汇编操作的dll函数时,程序报错,“内存不能读取或写入,可能是内存以损坏”。rn请各位高手指点一下,如何解决。
c# 调用 c dll
我在c#中调用 c 写的dll动态链接库,弄了好久,总是报“尝试读入或写入受保护的内存”这样的错误,估计是参数类型对应出错了。大家帮忙看下,下面这个动态库中的c语言函数转换成c#的函数,参数该是怎么样的呢?谢谢rnlong WINAPI OpenComPort(long Port, unsigned char *ComAdr, unsigned char * Baud,long *FrmHandle);
C#调用delphi的DLL报错
报的错是:尝试读取或写入受保护的内存。这通常指示其他内存已损坏。。rnrn我能保证这个dll没有错,而且有的机器运行正常,有的机器会报这个错。扫遍了百度和谷歌,方法我都试过但是还是出问题。有的说C#调用时参数加上ref,或者用char[],或者用byte[],我都试过,还是报这个错。问题的关键还是[color=#FF0000]delphi的pchar类型,C#用什么类型定义[/color]。rndelphi中的dll方法rnfunction MainDll(param1:Pchar):Boolean;stdcall;rnrnC#中的定义rnprivate const string str_fileDll = @"MainDLL.dll";rn [DllImport(str_fileDll, EntryPoint = "MainDLL", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]rn public static extern bool MainDll(string param1);//StringBuilder也报同样的错。rnC#调用rnif(MainDll("文本"))rnrn ;//此处报错:尝试读取或写入受保护的内存。这通常指示其他内存已损坏。。rn
C#调用C++的DLL报错
先上代码,这是C++函数的声明,有默认值的不用传值rn[code=c]rnextern "C" __declspec(dllexport) BOOL QK_AutoMarkFunEX(LPCSTR strPath,LPCSTR strTemplateFile,LPCSTR strOcrPath,LPCSTR strSetPath,rn int nType,LPCSTR strPostProcFile,LPCSTR& strErr,BOOL bCallBackFun = FALSE,rn CALLBACKFUNC cBFun= NULL,BOOL bParagragh = FALSE,BOOL bWordFromOcr = FALSE,PRODUCT_TYPE eProductType =PROD_JOURNAL);rnrn[/code]rnrn这是C#调用C++的代码rn[code=csharp]rn[DllImport("AutoMarkDll.dll", EntryPoint = "QK_AutoMarkFunEX", CallingConvention = CallingConvention.Cdecl)]rn public static extern bool QK_AutoMarkFunEX(String strPath,rn String strTemplateFile,rn String strOcrPath,rn String strSetPath,rn int nType,rn String strPostProcFile,rn ref String strErr);rn[/code]rnrn这是直接调用C#rn[code=csharp]rn String missing = null;rn String strErr = null;rn String path = @"E:\abc.pdf";rn String teplpath =@"E:\abc.xml";rn //bool b = InvokeClass.QK_AutoMarkFunEX(path, teplpath, missing, missing, 1, missing,ref strErr,false,null,false,false);rn bool b = InvokeClass.QK_AutoMarkFunEX(path, teplpath, missing, missing, 1, missing, ref strErr);rn Console.WriteLine(b);rn[/code]rnrn运行后报错,尝试读取或写入受保护的内存。这通常指示其他内存已损坏。rn请大家帮忙看下,怎么回事,我对C++不是很了解,急
C#调用C++ dll报错
我在C++中定义的函数为(并且编译成CPPDLL.dll,使用vs2010,win7-64b系统)rnextern"C" __declspec(dllexport) int enstr(int x,int y) rnrn return x+y;rnrnrn在C#中调用为rn [DllImport("CPPDLL.dll")]rn public static extern int enstr(int x,int y);rnrn结果报错rn[color=#FF0000]托管调试助手“PInvokeStackImbalance”在“E:\myprogram\test\Csharpe_CPP\CSharpe\bin\Debug\CSharpe.exe”中检测到故障。rn其他信息: 对 PInvoke 函数“CSharpe!CSharpe.CPPDLL::enstr”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。[/color]rnrn但是我查阅过C#中int和C++中int是匹配的,而且我将C#中改为INT32也同样报错,请大家帮帮忙,是什么原因
vb调用vc dll 参数为结构体 
如果在vc.dll的参数是结构体:rntypedef structrn BYTE m_bRemoteChannel;rn BYTE m_bSendMode;rn BYTE m_nImgFormat; rn char *m_sIPAddress;rn char *m_sUserName;rn char *m_sUserPassword;rn BOOL m_bUserCheck;rn HWND m_hShowVideo;rnCLIENT_VIDEOINFO, *PCLIENT_VIDEOINFO;rnrn在vb6中调用dll时rn指针参数应该如何如赋值呢????rnrnPrivate Type CLIENT_VIDEOINFOrn m_bRemoteChannel As Bytern m_bSendMode As Bytern m_bImgFormat As Bytern m_sIPAddress As Stringrn m_sUserName As Stringrn m_sUserPassword As Stringrn m_bUserCheck As Longrn m_hShowVideo As LongrnEnd TypernrnPrivate Declare Function MP4_ClientStart Lib "hikclient.dll" (nClentInfo As CLIENT_VIDEOINFO, ByVal lpEnumFunc As Long) As LongrnDim CV As CLIENT_VIDEOINFOrnrnDim strUserName As String * 127rnDim strUserPassWord As String * 127rnDim strIPAddress As Stringrn'rnstrUserName = "123"rnstrUserPassWord = "w"rnstrIPAddress = "192.168.52.218"rnrnCV.m_bRemoteChannel = 0rnCV.m_bSendMode = 0rnCV.m_bUserCheck = 1rnCV.m_sUserName = strUserNamernCV.m_sUserPassword = strUserPassWordrnCV.m_bImgFormat = 0rnCV.m_sIPAddress = strIPAddressrnCV.m_hShowVideo = Picture1.hWndrnrn调用dll函数一直不成功 rnrnRet = MP4_ClientStart(CV, 0&)rnrn请问我该如何如处理!
C结构体包含函数指针
#include <stdio.h>#include <malloc.h>struct person {    char *name; unsigned int age; void (*speak)(void); void (*eat)(void);};void speak_chinese(void){ printf("speak chinese!\n");}void ea...
返回值为List的报错
namespace Project_billrnrn public partial class MainForm : Formrn rn private List _lstChanel = new List();rn rn private void MainForm_Load(object sender, EventArgs e)rn rn //对_lstChanel的添加或删除rn rnrn publc List rtnList()rn rn return this._lstChanle;rn rn rnrn class myClassrn rnrn rnrnrn这里会对rtnList报一个Inconsistent accessibility: return type 'System.Collections.Generic.List' is less accessible than method 'Project_bill.MainForm.rtnList()' rnrn请问这是哪里的问题?
C#中怎么调用非托管的DLL,参数为双指针的结构体
typedef struct rn int hr_min_sec; //1st byte:second, 2nd byte:minute, 3rd byte:hourrn int micro_sec;rn S_Time;rnrntypedef struct rn int frame_id;rn char DLC, RTR, FF; rn unsigned char frame_data[8];rn S_Time frame_time; rn S_CANframe;rn这是我定义的结构体,在VC中的,同时还有这个函数:int CAN_frm_recv(S_CANframe **frame_buf),这个函数已经编写在VC中的MW70X.dll中了rn请问一下,这个函数我在C#中怎么调用这个函数?rn哪位大侠帮帮忙啊
C#调用C++的dll方法,返回值为结构
c++的D.dll里定义:rnrntypedef structrnrnchar a[10];rnlong b;rnSS;rnSS funA(char *p1,long p2);rnrnC#里:rn[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]rnpublic struct RESULTrnrn public byte[] a;rn [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.AnsiBStr, SizeConst = 10)]rn public int b;rnrn[DllImport("D.dll", EntryPoint = "funcA", CharSet = CharSet.Ansi)]rnpublic static extern RESULT func_A(StringBuilder p1,int p2);rnrnStringBuilder p1=new StringBuild("fff");rnRESULT res = func_A(p1,111);rn运行到这儿,直接退出!没有任何提示!rnrn请教高手!rn谢谢!
C#调用DLL的问题,程序直接退出,返回值为2
用C语言打包成DLL动态链接库供C#调用,C源程序中的矩阵乘法和求逆使用了MKL库函数,在C#中调用乘法和包含乘法的函数时,出现下面的错误:rn““test1.vshost.exe”(CLR v4.0.30319: test1.vshost.exe): 已加载“C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll”。已跳过加载符号。模块进行了优化,并且调试器选项“仅我的代码”已启用。rn程序“[7856] test1.vshost.exe”已退出,返回值为 2 (0x2)。”rnrn接着在工具->选项->调试中取消勾选“启用仅我的代码”,得到下面的错误提示:rnrn““test1.vshost.exe”(CLR v4.0.30319: test1.vshost.exe): 已加载“C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll”。已加载符号。rn程序“[20376] test1.vshost.exe”已退出,返回值为 2 (0x2)。”rnrn当不使用这些库函数而使用自己写的乘法和求逆的源程序时,则不会出现问题。rnrn劳烦各位有遇到类似问题的各位给一点提示之类的,谢谢
C#调用VC++的DLL,函数参数或返回值为CString
一个VC++写的DLL,函数参数带有字符串,调用不成功,后人家在VC++里又改成字符数组,我还是调用不成功.并且再试了很多方法时候,有些还会报尝试读取或写入受保护的内存,这通常指示其他内存已损坏
c# string返回值筛选
我用的百度AI识别图片,返回值如下:rnrn "log_id": 1398984202156276557,rn "direction": 0,rn "words_result_num": 2,rn "words_result": [rn rn "words": "小明是小狗",rn "probability": rn "variance": 0.0,rn "average": 0.999742,rn "min": 0.998732rn rn ,rn rn "words": "丽丽大帅哥",rn "probability": rn "variance": 0.000435,rn "average": 0.987731,rn "min": 0.946409rn rn rn ],rn "language": -1rnrnrn我不想要这么多内容,只需要WORDS的内容(小明是小狗 丽丽大帅哥),请教大神应该怎么写
调用Dll的返回值问题
我调用一个C写的Dll,里面有一个函数:rnBOOL __stdcall Fp_SetCallback(rnIN Fp_Callback_ pCallbackrn);rnrnrn参数:rnpCallback回调函数指针, 指向通过Fp_Callback_类型的回调函数, Fp_Callback_ 在FpDrv.h 中rn定义如下:rntypedef void (__stdcall *Fp_Callback_)(BYTE * const pBuffer,rnlong lBufferSize);rn其中, pBuffer 指向图像内存, lBufferSize 是图像数据大小, 以字节为单位。rn返回值:rn成功返回TRUE, 失败返回FALSE。rnrn请问在Delphi中应该如何定义p_Callback并调用?谢谢!
C#调用dll 参数是结构体 的问题。
[DllImport("APIHid.dll")]rnpublic static extern Int16 TransmitAPDU(int hic, ref APDUEx apdu);rnrn调用的时候是这样的。rnTransmitAPDU(0, ref apdu);rnTransimtAPDU会传出apdu结构,并且结构中的一个数组在函数中赋值。运行的时候到这一步总说我的rn“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”rn是我从dll导入时,声明函数参数错误吗?应该怎么写才对?rnrnps:apdu是一个结构体,如下:rn public struct APDUExrn rn public Byte sendlen;rn public Byte[] sendbuf;rn public Byte recvlen;rn public Byte[] recvbuf;rn rnrnrnrnrnrnrn
C# 调用C++ dll,结构体含有指针
C:rn[code=c]rnstruct MyStructrnrn MyStruct * next;rn int i;rn;rnrnextern "C" char test(MyStruct ms)rnrn return 's';rnrnrnrnextern "C" int t()rnrn return 1;rnrn[/code]rnrnC#:rn[code=csharp]rn [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]rn public struct MyStructrn rn public IntPtr next;rn public int i;rn ;rnrn [DllImport(@"ConsoleApplication2.dll", CharSet = CharSet.Unicode)]rn public static extern char test(MyStruct ms);rnrn [DllImport(@"ConsoleApplication2.dll", CharSet = CharSet.Unicode)]rn public static extern int t();rnrn static void Main(string[] args)rn rn rn rn int i = t();rnrnrn MyStruct m = new MyStruct();rn IntPtr pv = Marshal.AllocHGlobal(10);rn Marshal.WriteInt32(pv, 10);rn test(m);rnrnrn rn[/code]rnrn int i = t();可以成功。rn下面就错了rn如何调用test(m);rn对 PInvoke 函数“TestApi!TestApi.Program::test”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。rnrnrnrn
C#如何调用C++的DLL的结构体数组指针
C接口rnrnstruct PointVec3f//储存XYZ的坐标值.rn float xValue;rn float yValue;rn float zValue;rn;rnextern "C" __declspec(dllimport) void getPointCloud(PointVec3f *points, int pointNum);rnrnC#定义rnpublic struct PointVec3f rn rn [MarshalAs(UnmanagedType.R4)]rn public float xValue;rn [MarshalAs(UnmanagedType.R4)]rn public float yValue;rn [MarshalAs(UnmanagedType.R4)]rn public float zValue;rn ;rnPointVec3f[] points =new PointVec3f[NUM]; //points结构体数组的值我已经获取到了,想请问怎么传指针到PointVec3f *points中!Ref的方法试过了,不行!有没有其他方法,急!!rnrn private void button1_Click(object sender, EventArgs e)rn rn StreamReader strs = new StreamReader("扫描结果.txt",Encoding.Default);rn String [] s;rn int i;rn int j;rn j = 0;rn DisPlay.PointVec3f[] points = new DisPlay.PointVec3f[256000];rn // 结构体类型和IntPtr类型的大小rn int nSizeofRD = Marshal.SizeOf(typeof(DisPlay.PointVec3f));rn int nSizeofIntPtr = Marshal.SizeOf(typeof(IntPtr));rnrn // 转换为指针,首先建立一个与之同样大小的数组rn IntPtr[] pArray = new IntPtr[points.Length];rn //for (int i = 0; i < rData.Length; i++)rn pArray[0] = Marshal.AllocHGlobal(nSizeofRD * points.Length);rnrn // 将数组转换为一个指针rn IntPtr pRD = Marshal.AllocHGlobal(nSizeofIntPtr * 1);rnrn // 把C#结构体数组拷贝至这个指针rn Marshal.Copy(pArray, 0, pRD, 1);rn for (int k = 0; k < points.Length; k++)rn Marshal.StructureToPtr(points[k], (IntPtr)((UInt32)pRD + k * nSizeofRD), true);rnrn dissplay = new DisPlay();rn dissplay.init();rn string str = "";rn for (i = 0; i < NUM; i++)rn rn str = strs.ReadLine();rn if ((s = str.Split(' ')) == null)rn break;rn if ((s = str.Split(' ')) != null && "Profile" == s[0])rn rn strs.ReadLine();rn rn elsern rn points[j].xValue = float.Parse(s[1]);rn points[j].yValue = float.Parse(s[3]);rn points[j].zValue = float.Parse(s[2]);rn j++;rn Num++;rn rn rn DisPlay.getPointCloud( pRD , Num );rn DisPlay.show(this.Handle);
关于 Dll 返回值的问题(String)
请问从Dll中返回字符串值最保险的办法是什么呢?rnrn我是这样做的,rnrnfunction GetStrings: Pointer;stdcall;rnvarrn strResult: String;rnbeginrn .....rn strResult := 'Hello';rn .....rnrn Result := PChar(strResult);rnrnend;rnrnrn可是不太稳定,有时返回的值后面有乱码,请问是什么原因?
C#调用C++数组,结构体DLL
1.基本数据类型的传递 常见数据类型的传递   C/C++ C# 长度 short short 2Bytes int int 4Bytes long(该类型在传递的时候常常会弄混) int 4Bytes bool bool 1Byte char(Ascii码字符) byte 1Byte ...
C#调用c++ DLL传递结构体
typedef structrnrn char szServerName[KCBP_SERVERNAME_MAX + 1];rn int nProtocal;rn char szAddress[KCBP_DESCRIPTION_MAX + 1];rn int nPort;rn char szSendQName[KCBP_DESCRIPTION_MAX + 1];rn char szReceiveQName[KCBP_DESCRIPTION_MAX + 1];rn char szReserved[KCBP_DESCRIPTION_MAX + 1];rnrntagKCBPConnectOption;rnrnint SetConnectOption(tagKCBPConnectOption stKCBPConnection);rnrn不知如何调用,请大家指教。
c#调用c++ dll接口 的结构体
结构体c++定义为:rnstruct MyInfornrn unsigned long nID; rn unsigned long nParentID; rn char strName[MAX_TEXT_LEN]; rn char strMemo[MAX_MEM_LEN]; rn; rnrn当结构体在定义的函数中作为形参定义时,如何调用?rn如:rnpublic bool GetMyInfoByID(UInt32 ID, ref MyInfo[] deviceStation, ref UInt32 pCount)rnrn如何调用?
求助——C#调用C dll结构体的函数指针怎么写?
如题 新手求帮助rnc[code=c]typedef struct tagRVDrn rn void (*control_cmd) (int sn, unsigned char* data, int length);rn void (*bin_msg) (unsigned char* data, int length);rn void (*async_callback) (int sn, int result);rn RVD_t;rnrn RVD_Export int init_rvd (RVD_t* rvd,int id);rn RVD_Export void close_rvd (RVD_t* rvd);rn RVD_Export int req_cmd (int sn,const char* json);rn RVD_Export int _cmd (int sn,const char* json);[/code]rnrn在C#中调用怎么写啊
dll调用及返回值问题
用vc6.0写RKYdll32.DLL时这样写rnint Rky(int Pa,char *BFE)rn rn IF(pa=1)rn rn BUFFE= " ABCD ";rn rn return 0;rn rn 在VFP中rn DECLARE INTEGER Rky IN RkyDLL32.dll INTEGER , STRING @rnSTORE 1 TO PrnSTORE '' TO BFERrnRE = RKY(p,@BFER)rn为什么不会返回BFER="ABCD"呢,应怎样来修改dll文件才能得到re=0 BFER="ABCD"
c#调用c,c++ dll 嵌套结构体转换
现在用C#调用不知道是C还是C++写的DLL库,涉及到结构体嵌套时参数传递的问题,在网上找了各种方法都跟我这个不太一样,也试了各种方法都过不去,求助。rnc++结构体如下,DLL无法改写。rnrn[code=c]rn//被嵌套结构体rntypedef struct rnCHAR a[ 19 ];rnCHAR b;rnWORD c;rn OBE, *LPOBE;rnrn//外层结构体rntypedef struct rnDWORD d;rnOBE ObeInfo;rn CARD, *LPCARDT;rn[/code]rnrn尝试了C#的结构体定义如下:rn[code=csharp]rn//被嵌套结构体rn[StructLayout(LayoutKind.Sequential)]rnpublic struct OBE{rn[MarshalAs(UnmanagedType.ByValArray,SizeConst=19)]rnpublic char[] a;rnpublic char b;rnpublic uint16 c;rn}rnrn//外层结构体rn[StructLayout(LayoutKind.Sequential)]rnpublic struct CARDrnpublic uint d;rn//这个地方不知道怎么写了!!!rn[MarshalAs(UnmanagedType.Struct)]rnpublic OBE ObeInfo;rnrn[/code]rnrn报AccessViolationException异常,提示我正在访问不可读写的内存。rnrn以上。
VC++ DLL方法返回值为结构体类型用C#如何调用?
VC++结构体定义rntypedef struct _RESPONDDATArnrn WORD rdAddress; //设备地址rn WORD rdPacketNum; //数据包号rn WORD rdLength; //返回的数据长度rn BYTE rdRespond; //应答内容,DEV_ACK或DEV_NACKrn BYTE rdCmdCode; //命令代码rn BYTE rdData[RECV_BUFFER_SIZE]; //返回的数据内容rn RESPONDDATA, *PRESPONDDATA;rnrn接口声明:FUNEXPORT RESPONDDATA WINAPI LS_GetRespondData()rnrn现在我要用C#调用这个方法,可是一运行就报“方法的类型签名与 PInvoke 不兼容。”这个错误rnrn我在C#中是这样定义的rn结构体:rn [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] rn public struct RespondDatarn rn public Int16 rdAddress;rn public Int16 rdPacketNum;rn public Int16 rdLength;rn public Byte rdRespond;rn public Byte rdCmdCode;rnrn [MarshalAs(UnmanagedType.ByValArray,SizeConst=4096)]rn public Byte[] rdData;rn rnrn当时在调用这个方法的时候就报错了,请高手指点一下。
C#中调用c生成dll问题的结构体相关问题
如果我在c中的结构体定义如下rntypedef struct Tcl_Interp rn char *result; rn void (*freeProc)(char *blockPtr); rn int errorLine; rn Tcl_Interp;rnrn其中void (*freeProc)(char *blockPtr)是一个指向函数的指针。rn请问在c#中如何定义该结构体。rn例如:rn public class Tcl_Interprn rn const int RESULT_FULL_LEN = 0x200;rnrn [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RESULT_FULL_LEN)]rn public string result; rn //public IntPtr freeProc (string blockPtr); rn int errorLine; rn
C#调用非托管dll动态库返回值问题
函数原型:unsigned char* FindToken() 返回值是一个定长8字节的值rnrn我用C#如些调用:rn[DllImport("GDHidUserCtrl.dll", EntryPoint = "FindToken")]rn [return: MarshalAs(UnmanagedType.LPArray, SizeConst = 8)]rn internal static extern byte[] FindToken(); rn public static byte[] getUsbKey()rn rn return FindToken(); rn rnrn但运行时出现如下错误:rn无法封送处理“return value”: 无效的托管/非托管类型组合。 rn说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 rnrn异常详细信息: System.Runtime.InteropServices.MarshalDirectiveException: 无法封送处理“return value”: 无效的托管/非托管类型组合。rnrn源错误: rnrnrn行 26: public static byte[] getUsbKey()rn行 27: rn行 28: return FindToken(); rn行 29: rn行 30: rn rnrn源文件: e:\UsbKey\App_Code\UsbKeyClient.cs 行: 28 rnrn堆栈跟踪: rnrnrn[MarshalDirectiveException: 无法封送处理“return value”: 无效的托管/非托管类型组合。]rn UsbKeyClient.FindToken() +0rn UsbKeyClient.getUsbKey() in e:\UsbKey\App_Code\UsbKeyClient.cs:28rn testusbkey.Button1_Click(Object sender, EventArgs e) in e:\UsbKey\testusbkey.aspx.cs:20rn System.Web.UI.WebControls.Button.OnClick(EventArgs e) +75rn System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +98rn System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7rn System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11rn System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33rn System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4919rnrn 跪求各位高手帮小弟解决此问题,好急人啊!!!
相关热词 c# 标准差 计算 c#siki第五季 c#入门推荐书 c# 解码海康数据流 c# xml的遍历循环 c# 取 查看源码没有的 c#解决高并发 委托 c#日期转化为字符串 c# 显示问号 c# 字典对象池