C#:marshall字符串为utf8 char *

时间:2013-07-03 01:25:17

标签: c# .net pinvoke libspotify

背景

我正在尝试编写基于修改后的libspotify.net(http://libspotifydotnet.codeplex.com/)的高级libspotify包装器。 由于libspotify.net只是一个瘦(并且完全被错误...)pinvoke层,它不处理libspotify使用的utf8编码。

我的想法是将字符串转换为byte []并适当更改签名。

我有这个原生结构:

typedef struct sp_session_config {
  int api_version;                       
  const char *cache_location;           
  const char *settings_location;                    
  const void *application_key;           
  size_t application_key_size;           
  const char *user_agent;                
  const sp_session_callbacks *callbacks; 
  void *userdata;          
  bool compress_playlists;
  bool dont_save_metadata_for_playlists;
  bool initially_unload_playlists;
  const char *device_id;
  const char *proxy;
  const char *proxy_username;
  const char *proxy_password;
  const char *ca_certs_filename;
  const char *tracefile;

} sp_session_config;

工作版本:

    [DllImport("libspotify")]
    public static extern sp_error sp_session_create(ref sp_session_config config, out sp_session sessionPtr);

    public struct sp_session_config
    {
        public int api_version;
        public IntPtr cache_location;
        public IntPtr settings_location;
        public IntPtr application_key;
        public uint application_key_size;
        public IntPtr user_agent;
        public IntPtr callbacks;
        public IntPtr userdata;
        public bool compress_playlists;
        public bool dont_save_metadata_for_playlists;
        public bool initially_unload_playlists;
        public IntPtr device_id;
        public IntPtr proxy;
        public IntPtr proxy_username;
        public IntPtr proxy_password;
        public IntPtr ca_certs_filename;
        public IntPtr tracefile;
    }

此版本使用库将工作放在开发人员身上。

我的版本:

    public struct sp_session_config_internal
    {
        public int api_version;
        public byte[] cache_location;
        public byte[] settings_location;
        public byte[] application_key;
        public uint application_key_size;
        public byte[] user_agent;
        public IntPtr callbacks;
        public IntPtr userdata;
        public bool compress_playlists;
        public bool dont_save_metadata_for_playlists;
        public bool initially_unload_playlists;
        public byte[] device_id;
        public byte[] proxy;
        public byte[] proxy_username;
        public byte[] proxy_password;
        public byte[] ca_certs_filename;
        public byte[] tracefile;
    }


    [DllImport("libspotify", EntryPoint="sp_session_create")]
    private static extern sp_error sp_session_create_internal(ref sp_session_config_internal config, out sp_session sessionPtr);
    public static sp_error sp_session_create(ref sp_session_config config, out sp_session sessionPtr)
    {
        sp_session_config_internal config_internal = new sp_session_config_internal();
        config_internal.api_version = config.api_version;
        config_internal.application_key = config.application_key;
        config_internal.application_key_size = (uint)config.application_key.Length;
        config_internal.ca_certs_filename = SH.StringToUtf8Bytes( config.ca_certs_filename);
    ...
        var err = sp_session_create_internal(ref config_internal, out session);
    ...
    }

运行时,会在libspotify内发出以下错误:访问冲突读取位置0x000001c0 我用google搜索并在某处读取有时只复制第一个数组元素的地方。 我尝试使用

装饰所有数组
        [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U1)]

这给出了异常“无法编组'sp_session_config_internal'类型的字段'cache_location':无效的托管/非托管类型组合(数组字段必须与ByValArray或SafeArray配对)。”

TL;博士

使用IntPtr和手动编组的复杂解决方案,使用utf8字符串的字节数组的简单解决方案在库读取时会产生访问冲突。 有没有比使用intptr进行手动编组更简单的方法?

1 个答案:

答案 0 :(得分:3)

我已经解决了完全相同的问题 - 包装libspotify for .NET。我去了IntPtr路线,写了一个辅助类来进行编组。我发现阵列编组是完全令人抓狂的,不值得撕掉你的头发。

这是辅助类:

https://github.com/openhome/ohLibSpotify/blob/master/src/ohLibSpotify/Utf8String.cs#L99

简化版:

internal class Utf8String : IDisposable
{
    IntPtr iPtr;
    public IntPtr IntPtr { get { return iPtr; } }
    public int BufferLength { get { return iBufferSize; } }
    int iBufferSize;
    public Utf8String(string aValue)
    {
        if (aValue == null)
        {
            iPtr = IntPtr.Zero;
        }
        else
        {
            byte[] bytes = Encoding.UTF8.GetBytes(aValue);
            iPtr = Marshal.AllocHGlobal(bytes.Length + 1);
            Marshal.Copy(bytes, 0, iPtr, bytes.Length);
            Marshal.WriteByte(iPtr, bytes.Length, 0);
            iBufferSize = bytes.Length + 1;
        }
    }
    public void Dispose()
    {
        if (iPtr != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(iPtr);
            iPtr = IntPtr.Zero;
        }
    }
}

可以在这里看到用法:

https://github.com/openhome/ohLibSpotify/blob/master/src/ohLibSpotify/SpotifySession.cs#L104

public static SpotifySession Create(SpotifySessionConfig config)
{
    IntPtr sessionPtr = IntPtr.Zero;
    IntPtr listenerToken;
    using (var cacheLocation = SpotifyMarshalling.StringToUtf8(config.CacheLocation))
    using (var settingsLocation = SpotifyMarshalling.StringToUtf8(config.SettingsLocation))
    using (var userAgent = SpotifyMarshalling.StringToUtf8(config.UserAgent))
    using (var deviceId = SpotifyMarshalling.StringToUtf8(config.DeviceId))
    using (var proxy = SpotifyMarshalling.StringToUtf8(config.Proxy))
    using (var proxyUsername = SpotifyMarshalling.StringToUtf8(config.ProxyUsername))
    using (var proxyPassword = SpotifyMarshalling.StringToUtf8(config.ProxyPassword))
    using (var traceFile = SpotifyMarshalling.StringToUtf8(config.TraceFile))
    {
        IntPtr appKeyPtr = IntPtr.Zero;
        listenerToken = ListenerTable.PutUniqueObject(config.Listener, config.UserData);
        try
        {
            NativeCallbackAllocation.AddRef();
            byte[] appkey = config.ApplicationKey;
            appKeyPtr = Marshal.AllocHGlobal(appkey.Length);
            Marshal.Copy(config.ApplicationKey, 0, appKeyPtr, appkey.Length);
            sp_session_config nativeConfig = new sp_session_config {
                api_version = config.ApiVersion,
                cache_location = cacheLocation.IntPtr,
                settings_location = settingsLocation.IntPtr,
                application_key = appKeyPtr,
                application_key_size = (UIntPtr)appkey.Length,
                user_agent = userAgent.IntPtr,
                callbacks = SessionDelegates.CallbacksPtr,
                userdata = listenerToken,
                compress_playlists = config.CompressPlaylists,
                dont_save_metadata_for_playlists = config.DontSaveMetadataForPlaylists,
                initially_unload_playlists = config.InitiallyUnloadPlaylists,
                device_id = deviceId.IntPtr,
                proxy = proxy.IntPtr,
                proxy_username = proxyUsername.IntPtr,
                proxy_password = proxyPassword.IntPtr,
                tracefile = traceFile.IntPtr,
            };
            // Note: sp_session_create will invoke a callback, so it's important that
            // we have already done ListenerTable.PutUniqueObject before this point.
            var error = NativeMethods.sp_session_create(ref nativeConfig, ref sessionPtr);
            SpotifyMarshalling.CheckError(error);
        }
        catch
        {
            ListenerTable.ReleaseObject(listenerToken);
            NativeCallbackAllocation.ReleaseRef();
            throw;
        }
        finally
        {
            if (appKeyPtr != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(appKeyPtr);
            }
        }
    }

    SpotifySession session = SessionTable.GetUniqueObject(sessionPtr);
    session.Listener = config.Listener;
    session.UserData = config.UserData;
    session.ListenerToken = listenerToken;
    return session;
}

因为手动编写这些东西很快就会很繁琐,绝大多数包装器和DllImport声明都是从api.h头文件自动生成的。 (因此,你不会在github repo中找到它们,你需要下载项目并构建它以查看所有生成的代码。)

它都是自由许可的(2条款BSD),所以请随意使用它或借用它。