C无符号'char**out'到C#`byte[]`
这是libeay32.dll()中的函数: 如何用C#来描述它(如果我想得到一个字节[]) 代码: 我不喜欢这样,因为我认为结果是unicode 回答C无符号'char**out'到C#`byte[]`,c#,c,openssl,marshalling,dllimport,C#,C,Openssl,Marshalling,Dllimport,这是libeay32.dll()中的函数: 如何用C#来描述它(如果我想得到一个字节[]) 代码: 我不喜欢这样,因为我认为结果是unicode 回答 [DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)] public extern static int i2o_ECPublicKey(IntPtr encKey, ref IntPtr outPar); [DllImp
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public extern static int i2o_ECPublicKey(IntPtr encKey, ref IntPtr outPar);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int i2o_ECPublicKey(IntPtr encKey, int outPar);
//Pass *out as null for required buffer length.
int reqLen = i2o_ECPublicKey(k, 0);
Byte[] outBuf = new Byte[reqLen];
IntPtr unmanagedOut = Marshal.AllocCoTaskMem(outBuf.Length);
int res = i2o_ECPublicKey(k, ref unmanagedOut);
if (res == reqLen)
{
unmanagedOut -= reqLen; // because i2o_ECPublicKey add size to unmanagedOut
Marshal.Copy(unmanagedOut, outBuf, 0, outBuf.Length);
}
Marshal.FreeCoTaskMem(unmanagedOut);
我认为要手动执行此操作,需要使用Marshal.Copy将数组从非托管内存复制到托管字节[]。(注意,代码未经测试)
通过使用
GetBytes
StringBuilder outPar;
string result = "";
byte[] parbytes = System.Text.Encoding.Unicode.GetBytes(outPar.ToString());
foreach(byte parbyte in parbytes)
{
result+= Convert.ToChar(parbyte);
}
return result;
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public extern static int i2o_ECPublicKey(IntPtr encKey, ref IntPtr outPar);
[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public static extern int i2o_ECPublicKey(IntPtr encKey, int outPar);
//Pass *out as null for required buffer length.
int reqLen = i2o_ECPublicKey(k, 0);
Byte[] outBuf = new Byte[reqLen];
IntPtr unmanagedOut = Marshal.AllocCoTaskMem(outBuf.Length);
int res = i2o_ECPublicKey(k, ref unmanagedOut);
if (res == reqLen)
{
unmanagedOut -= reqLen; // because i2o_ECPublicKey add size to unmanagedOut
Marshal.Copy(unmanagedOut, outBuf, 0, outBuf.Length);
}
Marshal.FreeCoTaskMem(unmanagedOut);
public extern static int i2o_ECPublicKey (IntPtr encKey, ref IntPtr outPar);
...
//Pass *out as null for required buffer length.
int reqLen = i2o_ECPublicKey(key, null);
Byte[] outBuf = new Byte[reqLen];
IntPtr unmanagedOut = Marshal.AllocCoTaskMem(outBuf.Length);
int res = i2o_ECPublicKey(key, ref unmanagedOut);
if (res == 1) {
Marshal.Copy(unmanaged, outBuf, 0, outBuf.Length);
}
Marshal.FeeCoTaskMem(unmanagedOut);
StringBuilder outPar;
string result = "";
byte[] parbytes = System.Text.Encoding.Unicode.GetBytes(outPar.ToString());
foreach(byte parbyte in parbytes)
{
result+= Convert.ToChar(parbyte);
}
return result;