Search code examples
c#-3.0compact-frameworkpinvokewindows-ce

pinvoking function not suceeding


I'm trying to call this function in .net compact framework from an unmanaged dll that the device manufacter gave me:

Bool GetModelInfo(LPTSTR pszInfo, DWORD dwInfoType);

the infoType is one of the following enum:

enum ModemInfoType{
    Model_name,
    Model_revision,
    Model_IMEI,
    Model_IMSI
};

My actual pinvoke call is the following:

[System.Runtime.InteropServices.DllImportAttribute(gsmaAdapterDLLName, EntryPoint = "#36", CallingConvention = CallingConvention.Winapi)]   
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
    internal static extern bool GetModelInfo([System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)] out string pszInfo, uint dwInfoType);

I know that they must have build the string, just don't know if i should be passing an stringBuilder instead of an string. The problem is that i get an NotSupportedException when try to run the call to the function.

    /// <summary>
    /// Gets the modem info.
    /// </summary>
    /// <param name="modemInfo">The modem info.</param>
    /// <param name="infoRequested">The info requested.</param>
    /// <returns></returns>
    public bool GetModemInfo(out string modemInfo, NativeHelper.ModemInfoType infoRequested)
    {
        String _mymodemInfo;
        if (NativeImports.GetModelInfo(out _mymodemInfo, (uint)infoRequested) == true)
        {
            modemInfo = _mymodemInfo;
            return true;
        }
        else
        {
            modemInfo = "";
            return false;
        }
    }

That's my wrapper function that calls the native method


Solution

  • Calling by ordinal is brittle, so I'm dubious of the call in the first place, but given that, I'd try this:

    [DllImport(gsmaAdapterDLLName, EntryPoint = "#36")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool GetModelInfo(StringBuilder pszInfo, ModemInfoType dwInfoType);
    
    private string GetModelName()
    {
        StringBuilder sb = new StringBuilder(1024);
        if (!GetModelInfo(sb, ModemInfoType.Name))
        {
            throw new Exception("Call failed");
        }
        return sb.ToString();
    }