c# 通过 p/invoke 使用 c的加密程序 参数传递问题

最近项目中使用需要上位机和下位机通过rs232通信,涉及到通讯加密问题,

硬件那边主要是pcb layout的,于是我就把加密的活拦了过来,锻炼锻炼

首先说明问题:

在c中,加密解密都测试通过,然后在c#中调用后,发现解密字符串对不上

c代码如下:

	//扩展DES加密,明文可以为任意长度
	char* Encrypt(const char *str, const char password[8], int lenOfStr);

	///扩展DES解密,密文长度必须为的倍数
	char* Decrypt(const char *str, const char password[8], int lenOfStr);

c#代码如下:

        [DllImport("DesDLL.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern string Encrypt(string bytes_data, string bytes_password, int length);

        [DllImport("DesDLL.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern string Decrypt(string bytes_data, string bytes_password, int length);

排除问题:在函数中添加弹出框来查看结果,发现在c中用messagebox弹出来的和我得到的返回值一摸一样,这样就排除了参数传递错误的异常,

应该是在编码格式上出了问题

查阅资料,得知 c 中的 char* 是ascii编码的,而我们c#使用的字符串,默认是unicode的,这就导致了字符乱码

既然是编码格式问题,那我们就从格式入手,在dllimport中指定参数传递的格式

c#代码如下:

        [DllImport("DesDLL.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
        public static extern string Encrypt(string bytes_data, string bytes_password, int length);

        [DllImport("DesDLL.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
        public static extern string Decrypt(string bytes_data, string bytes_password, int length);

 ok,问题完美解决

原文地址:https://www.cnblogs.com/trenail/p/3445909.html