Search code examples
c#windows-mobiledllimport

_tcscmp error in C++ dll


I am writing a DLL function called ADAuthenticate that will authenticate a user against Active Directory and check a certain attribute of the user if he/she exists. If the administrator is authenticating, I do not want to the function to do an ldap search so I have the following if statement below:

if (_tcsicmp(username, TEXT("administrator")) != 0 && _tcscmp(attrs[0], TEXT("")) != 0)
                {
                    // Search for specific attributes
                    ldap_response = ldap_search_s(ldap, domain, LDAP_SCOPE_SUBTREE, search, attrs, 0, &ldap_msg);

                    if (ldap_response != LDAP_SUCCESS)
                        MessageBox(h_wnd, ldap_err2string(ldap_response), TEXT("ERROR - ldap_search_s"), MB_OK);
                    else if ((new_ldap_msg = ldap_first_entry(ldap, ldap_msg)) != NULL)
                    {
                        do 
                        {
                            // Append a pipe character if more than one attribute is requested
                            if (count > 0)
                                _tcscpy(ret_val, TEXT("|"));

                            _tcscpy(ret_val, *(ldap_get_values(ldap, new_ldap_msg, attrs[count++])));
                        } while ((new_ldap_msg = ldap_next_entry(ldap, ldap_msg)) != NULL);
                    }
                }

In the if statement, if I remove one of the string comparison operations (either one), it works fine. Once I put the two together, or even in nested if statements my whole program that calls on this function crashes. Anyone know what might be causing this?

The following is my header for the function:

extern "C" __declspec(dllexport) LPCTSTR ADAuthenticate(TCHAR * username, TCHAR * password, TCHAR * server,
                                                        TCHAR * backup_server, TCHAR * domain, HWND h_wnd,
                                                        TCHAR ** attrs)

This is how I am importing the DLL function:

[DllImport("WM_LDAP.dll")]
        public static extern IntPtr ADAuthenticate(string username, string password, string server, 
            string backup_server, string domain, IntPtr hWnd, string [] attrs);

Solution

  • Aha! Figured out what happened. My function returns a LPCTSTR and within it I had an LPTSTR variable called ret_val that I was using as the return variable. I didn't have it initialized and when I would try to _tcscpy() a value in to ret_val the program crashed. Initializing the value to LPTSTR ret_val = new TCHAR [128]; seems to work ok. It's weird though because the DLL worked fine with only one if statement even without initializing the variable... Gotta get used to that Windows-based C++/CLI stuff. It can get confusing.

    Thanks!