我试图使用我在Borland C ++ Builder中编码的C ++非托管DLL中的类。然后我想在C#中使用这段代码。
我使用P / Invoke从dll导入函数,然后我尝试将其包装在C#托管DLL中。我有一些重载错误和无效的参数。这可能来自我错误的使用方式" ref"而不是"指针"但我不知道如何调整它。我知道我可能做错了,但我不知道该怎么做,请试着指导我。
C ++非托管DLL:
Test.cpp的
#include <basepch.h>
#pragma hdrstop
#include "Test.h"
//-------------------
#pragma package(smart_init)
__fastcall TTest::TTest()
{
//rien
}
__fastcall TTest::~TTest()
{
//rien
}
void __fastcall TTest::setNombre(int nbr)
{
nombre = nbr;
}
int __fastcall TTest::getNombre()
{
return nombre;
}
Test.h
//---------------------------------------------------------------------------
#ifndef TestH
#define TestH
#include <SysUtils.hpp>
#include <Classes.hpp>
#include <string.h>
#include <stdio.h>
#include <StrUtils.hpp>
#include <time.h>
//---------------------------------------------------------------------------
class PACKAGE TTest
{
private:
int nombre;
protected:
public:
__fastcall TTest();
__fastcall ~TTest();
void __fastcall setNombre(int nbr);
int __fastcall getNombre();
};
extern PACKAGE TTest *Test;
//---------------------------------------------------------------------------
#endif
C#托管DLL :
ManagedClasseTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ManagedClasseTest
{
struct TUnmanagedClasseTest
{
private ref int nombre;
[DllImport("ClasseTest.dll",
EntryPoint="@TTest@$bctr$qqrv",
CallingConvention=CallingConvention.ThisCall)]
public static extern void ctor(ref TUnmanagedClasseTest c);
[DllImport("ClasseTest.dll",
EntryPoint="@TTest@$bdtr$qqrv",
CallingConvention=CallingConvention.ThisCall)]
public static extern void dtor(ref TUnmanagedClasseTest c);
[DllImport("ClasseTest.dll",
EntryPoint="@TTest@setNombre$qqri",
CallingConvention=CallingConvention.ThisCall)]
public static extern void setNombre(ref TUnmanagedClasseTest c, int nbr);
[DllImport("ClasseTest.dll",
EntryPoint="@TTest@getNombre$qqrv",
CallingConvention=CallingConvention.ThisCall)]
public static extern int getNombre(ref TUnmanagedClasseTest c);
public static void Uctor(ref TUnmanagedClasseTest c) {
ctor(c);
}
public static void Udtor(ref TUnmanagedClasseTest c) {
dtor(c);
}
public static void UsetNombre(ref TUnmanagedClasseTest c, int i) {
nombre = setNombre(c, i);
}
public static int UgetNombre(ref TUnmanagedClasseTest c) {
return getNombre(c);
}
}
public class ManagedClasseTest
{
public void ManagedClasseTest()
{
Umct = new TUnmanagedClasseTest();
TUnmanagedClasseTest.Uctor(Umct);
}
public void ~ManagedClasseTest()
{
TUnmanagedClasseTest.Udtor(Umct);
}
public void MsetNombre(int nombre)
{
TUnmanagedClasseTest.UsetNombre(Umct, nombre);
}
public int MgetNombre()
{
return TUnmanagedClasseTest.UgetNombre(Umct);
}
private ref TUnmanagedClasseTest Umct;
}
}