[英]How do I return a byte array from C++ to C#
So I've been struggling with this for a little bit. 所以我一直在努力解决这个问题。 I'm trying to make my own AES 128 library to use with one of my programs. 我正在尝试将自己的AES 128库用于我的一个程序。 The library tests out and works in C++ (well for the encrypt function.. I haven't implemented the others) The 'Encrypt' function is like this: 该库测试并在C ++中工作(适用于加密功能..我还没有实现其他功能)'加密'功能是这样的:
NEW CODE 新代码
void Aes128Class::EncryptBlock(BYTE* outBlock, const BYTE* inBlock, const BYTE* cipherBlock)
{
BYTE temp[16] = {0x00};
Galois::XorBlock(temp, inBlock);
Galois::XorBlock(temp, cipherBlock);
BYTE expandedKey[176] = {0x00};
memcpy(expandedKey, Key, 16);
Galois::expand_key(expandedKey);
Galois::XorBlock(temp, expandedKey);
for(int i=16; i<160; i+=16)
{
Galois::DoRound(temp, &expandedKey[i]);
}
Galois::SubBytes(temp);
Galois::ShiftRows(temp);
Galois::XorBlock(temp, &expandedKey[160]);
memcpy(outBlock, temp, 16);
}
void Aes128Class::EncryptData(BYTE* outBlock, size_t& outlen, const BYTE* inBlock, size_t length)
{
float blockSize = (float)(length/16);
blockSize = ceilf(blockSize);
int newLength = (int)(blockSize*16);
BYTE* temp = (BYTE*)malloc(newLength);
BYTE* padd = (BYTE*)malloc(newLength);
memset(temp, 0, newLength);
memcpy(padd, inBlock, length);
EncryptBlock(temp, padd, IV);
for (int i=1; i<blockSize; i++)
{
EncryptBlock(&temp[i*16], &padd[i*16], &temp[(i-1)*16]);
}
outlen = newLength;
memcpy(outBlock, temp, newLength);
}
The idea is that if the plainText
is not in a 16-byte block increment then I force it to be. 我们的想法是,如果plainText
不是16字节的块增量,那么我强制它。 So this makes for a variable size byte array. 所以这就产生了一个可变大小的字节数组。 It works in my C++
tests, but when I call it in C#
I get a few different errors... This will take a minute to describe. 它适用于我的C++
测试,但是当我在C#
调用它时,我会遇到一些不同的错误......这需要花一点时间来描述。
[DllImport("CppAes128.dll", CallingConvention = CallingConvention.ThisCall,
EntryPoint = "?EncryptData@Aes128Class@@QAEXPAEAAIPBEI@Z")]
static extern void EncryptData(IntPtr pClass, ref IntPtr outblock, [Out]int OutLength, byte[] inBlock, int length);
When I call this I get valid pointers to both the array
, and the outlength. 当我调用它时,我得到了有关array
和outlength的有效指针。 The way it looks right now causes an access violation, but I can get that structure to work if I change [Out]int OutLength
to ref IntPtr
. 它现在看起来的方式导致访问冲突,但如果我将[Out]int OutLength
为ref IntPtr
,我可以使该结构起作用。 Interestingly, if I do ref int
or ref uint
it still "works". 有趣的是,如果我做ref int
或ref uint
它仍然“有效”。 So if I do that I try to read the intptr
and then I get an access violation. 所以,如果我这样做,我会尝试读取intptr
然后我得到访问冲突。 I am compiling this as a x86 project
in .NET 4.0
(since I read somewhere that 3.5 had some bugs with access...) 我正在将其编译为.NET 4.0
的x86 project
(因为我在某处看到3.5有一些访问错误...)
Here is what I've tried in C#
. 这是我在C#
尝试过的。 It's a little garbled as I've been playing with it for hours (sorry): 这有点乱,因为我已经玩了好几个小时(对不起):
public byte[] EncryptData(byte[] plainText, int length)
{
byte[] enc = null;
int len = 0;
IntPtr pArray = IntPtr.Zero;
EncryptData(theClass, ref pArray, len, plainText, length);
Console.WriteLine(len);
//enc = new byte[len];
//Marshal.Copy(pArray, enc, 0, len);
//Marshal.Release(pArray);
//try
//{
// int elementSize = Marshal.SizeOf(typeof(IntPtr));
// //IntPtr unmanagedArray = Marshal.AllocHGlobal(10 * elementSize);
// Console.WriteLine("Reading unmanaged memory:");
// // Print the 10 elements of the C-style unmanagedArray
// for (int i = 0; i < 10; i++)
// {
// Console.WriteLine("{0:X2}:", Marshal.ReadByte(pArray, i));
// }
// Marshal.FreeHGlobal(pArray);
//}
//catch (Exception ex)
//{
// Console.WriteLine("{0}\n{1}", ex.Source, ex.Message);
// Console.WriteLine("Win32({0})", Marshal.GetLastWin32Error());
//}
//Marshal.Release(pArray);
return enc;
}
The only time this worked is when I just made a static-size array and didn't use ref
or marshal
copy or anything.. I think my signature was something like this 这个工作的唯一一次是我刚制作一个静态大小的数组并且没有使用ref
或marshal
副本或任何东西..我认为我的签名是这样的
static extern void EncryptData(IntPtr pClass, byte[] outBlock, byte[] inBlock, int length);
That almost worked, but the problem was that when I did a foreach
loop on that array
it was always the size that i put.. frustrating to say the least. 这几乎可以工作,但问题是,当我在那个array
上做了一个foreach
循环时,它总是我放的大小...至少可以说令人沮丧。
So what am I doing wrong? 那么我做错了什么? how can I get this to work? 我怎么能让这个工作? I am so frustrated with it. 我很沮丧。 Thank you 谢谢
Oh and FYI, this is so I cannot be dependent on the cryptlib
anymore. 哦,仅供参考,这是我不能再依赖于cryptlib
了。 I'm trying to recompile a different project, which uses cryptlib
, as a static library and not shared, which causes some problems with my compiled options and is too big of a hassle to change back. 我正在尝试重新编译一个使用cryptlib
的不同项目作为静态库而不是共享,这会导致我的编译选项出现一些问题,而且回头的麻烦太大了。
EDITED to show more code 已编辑以显示更多代码
This is the tests that I use. 这是我使用的测试。 I found a webpage that showed a bunch of tests, so this is me implementing this. 我找到了一个显示大量测试的网页,所以这就是我实现这一点。
void VerifyEncrypt16(const BYTE* expected, const BYTE* key, const BYTE* iv, const BYTE* plainText)
{
BYTE actual[16] = {0x00};
Aes128Class aes;
aes.SetKey(key, 16);
aes.SetIV(iv, 16);
size_t len = 0;
aes.EncryptData(actual, len, plainText, 16);
_ASSERT(CompareTwoArrays(expected, actual));
}
void VerifyEncrypt16String(const char* expected, const char* key, const char* iv, const char* plainText)
{
BYTE e[16];
BYTE k[16];
BYTE i[16];
BYTE p[16];
ByteUtil::StringToHex(expected, e);
ByteUtil::StringToHex(key, k);
ByteUtil::StringToHex(iv, i);
ByteUtil::StringToHex(plainText, p);
VerifyEncrypt16(e, k, i, p);
}
void CheckEncrypt16(void)
{
_RPT0(_CRT_WARN, "Checking Encryption of a 16 byte number IV set to 0\n");
//AESVS GFSbox test data for CBC
VerifyEncrypt16String("0336763e966d92595a567cc9ce537f5e","00000000000000000000000000000000","00000000000000000000000000000000","f34481ec3cc627bacd5dc3fb08f273e6");
VerifyEncrypt16String("a9a1631bf4996954ebc093957b234589","00000000000000000000000000000000","00000000000000000000000000000000","9798c4640bad75c7c3227db910174e72");
VerifyEncrypt16String("ff4f8391a6a40ca5b25d23bedd44a597","00000000000000000000000000000000","00000000000000000000000000000000","96ab5c2ff612d9dfaae8c31f30c42168");
VerifyEncrypt16String("dc43be40be0e53712f7e2bf5ca707209","00000000000000000000000000000000","00000000000000000000000000000000","6a118a874519e64e9963798a503f1d35");
VerifyEncrypt16String("92beedab1895a94faa69b632e5cc47ce","00000000000000000000000000000000","00000000000000000000000000000000","cb9fceec81286ca3e989bd979b0cb284");
VerifyEncrypt16String("459264f4798f6a78bacb89c15ed3d601","00000000000000000000000000000000","00000000000000000000000000000000","b26aeb1874e47ca8358ff22378f09144");
VerifyEncrypt16String("08a4e2efec8a8e3312ca7460b9040bbf","00000000000000000000000000000000","00000000000000000000000000000000","58c8e00b2631686d54eab84b91f0aca1");
//AESVS KeySbox test data for CBC
VerifyEncrypt16String("6d251e6944b051e04eaa6fb4dbf78465","10a58869d74be5a374cf867cfb473859","00000000000000000000000000000000","00000000000000000000000000000000");
//A TON OF MORE TESTS! etc etc etc VerifyEncrypt16String("5c005e72c1418c44f569f2ea33ba54f3","00000000000000000000000000000000","00000000000000000000000000000000","fffffffffffffffffffffffffffffffe");
VerifyEncrypt16String("3f5b8cc9ea855a0afa7347d23e8d664e","00000000000000000000000000000000","00000000000000000000000000000000","ffffffffffffffffffffffffffffffff");
}
Frankly, I've found the easiest way to do this is to wrap the unmanaged C++ call with a managed C++ call. 坦率地说,我发现最简单的方法是使用托管C ++调用包装非托管C ++调用。 In the managed C++, you can copy the data in a straight forward C++ manner (by pinning the data structure) and passing it back to C# 在托管C ++中,您可以以直接的C ++方式复制数据(通过固定数据结构)并将其传递回C#
In case you are still looking for answer, this example gives a starting point. 如果您仍在寻找答案,此示例给出了一个起点。
Basically, start from allocate memory block in native function call, than invoke call - back to managed where you pass ( by ref ) array and its size saved from the original list of input parameters. 基本上,从本机函数调用中分配内存块开始,而不是调用回调到托管的地方(通过ref)数组,并从原始输入参数列表中保存它的大小。
This way you allocate memory block for managed code in managed code and edit it with content from native. 这样,您可以为托管代码中的托管代码分配内存块,并使用本机内容编辑内存块。
http://msdn.microsoft.com/en-us/library/ektebyzx.aspx http://msdn.microsoft.com/en-us/library/ektebyzx.aspx
An alternate method would be nice to find, performance compare would be a bonus :) 另一种方法很好找,性能比较会是一个奖励:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.