c# - C 无符号 `char ** out` 到 C# `byte[]`

标签 c# c openssl marshalling dllimport

这是 libeay32.dll ( openssl project ) 中的函数:

int i2o_ECPublicKey (EC_KEY * key, unsigned char ** out)

如何用C#描述(如果我想获取一个字节[])?

代码:

[DllImport(DLLNAME, CallingConvention = CallingConvention.Cdecl)]
public extern static int i2o_ECPublicKey (IntPtr encKey, StringBuilder outPar);

我不喜欢这个,因为我认为结果是unicode。

回答

        [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 将数组从非托管内存复制到托管 byte[] 中。 (注意,代码未经测试)。

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);

关于c# - C 无符号 `char ** out` 到 C# `byte[]`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16653454/

相关文章:

c# - 使用 Xamarin.Forms 中的转换器替换图像

c# - View 和表之间的 Entity Framework 映射关联

c# - TFS 2010 API 文档

C 程序 - 链表问题

c - 为什么这样的文件或目录 <cblas.h> 不存在?

c - openssl RSA公钥与从C代码读取的 key 不匹配

c - OpenSSL 上的 AES CTR 256 加密操作模式

c# - 将语音合成器导入 Storyboard

c# - 如何将 pinvoke 用于指向 C# 的 C 结构数组指针

scala - Akka Stream TLS 服务器日志记录和故障排除