首页 > 解决方案 > 为什么我在使用 C# 调用 OCX C++ 代码时遇到问题

问题描述

使用 C# 调用 OCX 方法时出现问题。OCX 组件是用 C++ 开发的。

我收到此错误:

"System.Runtime.InteropServices.COMException (0x80020005): Los tipos
 no coinciden. (Excepción de HRESULT: 0x80020005
 (DISP_E_TYPEMISMATCH))\r\n   en
 System.RuntimeType.ForwardCallToInvokeMember(String memberName,
 BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData&
 msgData)\r\n   en
 MFCActiveXControl1Lib._DMFCActiveXControl1.LeoCadena(IntPtr
 nombreFichero, IntPtr contenidoFichero, Int32 LongitudFichero)\r\n  
 en AxMFCActiveXControl1Lib.AxMFCActiveXControl1.LeoCadena(IntPtr
 nombreFichero, IntPtr contenidoFichero, Int32 longitudFichero) en
 c:\\Temp\\PrinterManager\\Test\\MFCActiveXControl1\\Debug\\AxMFCActiveXControl1Lib.cs:línea
 43\r\n   en TestPrinterManager.Form1.button2_Click(Object sender,
 EventArgs e) en
 C:\\Temp\\PrinterManager\\Test\\TestPrinterManager\\TestPrinterManager\\Form1.cs:línea
 77"

C++ 签名是:

*void flushFiles();
LONG LeoCadena(unsigned char * nombreFichero,
             unsigned char * contenidoFichero,
             int LongitudFichero);*

我已经修改了生成的 Visual Studio 包装器,以便导出的方法是:

文件:

*void  flushFiles()
int32  LeoCadena(native int nombreFichero, 
             native int contenidoFichero,
             int32 LongitudFichero)*

cs文件:

*public virtual void flushFiles()
public virtual int LeoCadena(System.IntPtr nombreFichero, System.IntPtr contenidoFichero, int 
                             longitudFichero)*

当我使用 C# 调用该方法时,我使用了以下代码:

*string file_xml = @"C:\proyectos\fichero.xml";
string texto_xml;
System.IO.StreamReader sr = new System.IO.StreamReader(file_xml);
texto_xml = sr.ReadToEnd();
sr.Close();
sr.Dispose();
byte[] arr = Encoding.ASCII.GetBytes(texto_xml);
int longitud = arr.Length; 
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * arr.Length);
Marshal.Copy(arr, 0, ptr, longitud);
axMFCActiveXControl1.LeoCadena(ptr, ptr, longitud);
Marshal.FreeHGlobal(ptr);*

你知道我为什么会收到这个错误吗?

我使用 32 位平台和 .Net Framework 4.5.2

标签: c#c++cominteropocx

解决方案


推荐阅读