如何在c++中调用c#方法?
How do you call a c# method in c++?
这里和这里他们确实谈论该做什么,但我似乎无法在c++中找到我的c#项目。
我已经添加了c#项目作为c++项目的参考,但每当我尝试使用我需要的方法时,它找不到命名空间。我通过右键单击c++项目并选择"参考"来添加它,然后添加c#项目并添加新参考。两个项目在同一个解决方案中。
在下面的代码示例中,我给出了完整的c#代码(除了使用)和一部分c++代码(我试图调用c#方法的方法)。我还更改了一些名称空间,使其更通用,并且不包含敏感信息。
c#代码是这样的:
namespace Company.Pins.Bank.Decryption
{
public class Decrypt
{
[DllImport("decryptsn.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr decryptsn(byte[] InpData);
//__declspec(dllimport) char* decryptsn(char* InpData);
public static String Decryption(string param2)
{
byte[] InpData = new byte[255];
InpData = StrToByteArray(param2);
return Marshal.PtrToStringAnsi(decryptsn(InpData));
}
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
}
}
c++代码CPReSInterfaceApp theApp;
extern "C" DllExport BOOL WINAPI UserInstruction(
HWND hWnd, HINSTANCE hInst, double* lpNumeric,
TCHAR* lpAlpha1, TCHAR* lpAlpha2)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if (lpNumeric == NULL || lpAlpha1 == NULL || lpAlpha2 == NULL)
return FALSE;
ReconcileUHParameter(lpNumeric, lpAlpha1, lpAlpha2);
int iCommand = (int)lpNumeric[0];
lpNumeric[0] = 6;
lpAlpha2 = Company.Pins.Bank.Decryption.Decrypt.Decryption("123456");
return TRUE;
}
你需要在代码中添加一个#using指令。例如,如果您的c# dll被命名为Decrypt.dll
,请将此添加到您的c++编译器的顶部:
#using "Decrypt.dll"
您还需要确保调用托管方法的c++代码也使用/clr
编译器选项编译为托管。
另外,我认为您需要使用::
作为名称空间分隔符,而不是.
。
lpAlpha2 = Company::Pins::Bank::Decryption::Decrypt::Decryption("123456");
相关文章:
- 如何强制从重写方法调用重写的方法基方法?
- C++:使用方法调用析构函数的顺序是什么?
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 指向类方法调用的指针
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 是否有可以处理方法调用依赖关系的设计模式?
- 如何缩短C++中的方法调用?
- 从部分专用模板方法调用模板非静态方法
- 有没有办法禁止派生类中的基类方法调用?
- 为什么这C++只在编译器上编码一个不明确的方法调用Microsoft?
- 从父方法调用子方法
- 如何将子方法调用到父方法
- 虚拟函数在哪里使用 vpointer to vtable 来解析方法调用,非虚拟方法存储在哪里以及如何解析它们?
- 从静态方法调用静态函数指针
- 从同一类中的另一个方法调用方法时出错
- 方法调用意外地像 l 值一样起作用
- 无法从派生的一个方法调用基类方法
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- C 多线程JAVA JNI方法调用