none
Not able to assign values to CString varibles declared in Header File RRS feed

  • Question

  • In my C# project solution,  i had one C++ project and i am accessing C++ methods from the C#  using DllImport.

    In that C++ project we are not able to assign values to  all CString member variables that are declared in header files and the CString variables that are declared in .cpp files are working fine. More over if we run the C++ project independently its also working fine.

    The following is my dll wrapper in C#

    [DllImport(@"Path.dll")]
    private static unsafe extern long SetPathName([param: MarshalAs(UnmanagedType.LPStr)] String path);
    The below C++ snippet is the method definition for the above wrapper

    long CSUTCtrl::SetFileLogPathName(LPCTSTR FilePathName) 
    {
    	CString m_CPUNameLocal=FilePathName;
    	m_CPUName = m_CPUNameLocal;
    }
    For  m_CPUNameLocal value gets assigned but for m_CPUName of type CString declared in header file, while assigning throws an error

    An exception of type 'System.AccessViolationException' occurred in Path.dll and wasn't handled before a managed/native boundary

    Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

    Please help me to fix this.

    Gowtham

    Monday, January 28, 2013 4:48 PM

Answers

  • The question is not what are you passing but what is expected by the function. Is it expecting char* or wchar_t* as parameter?

    Another thing which might be of interest is the signature of the SetPathName. Is it the same as that SetFileLogPathName method?

    Are you sure you're using the correct calling convention? Default is StdCall. You might try using CallingConvention.Cdecl for your DllImport.

    Tuesday, January 29, 2013 9:00 AM

All replies

  • You're passing a char* (LPStr). The C++ function expects LPCTSTR, which is either char* or wchar_t*. If UNICODE is defined, your types don't match.
    Monday, January 28, 2013 5:01 PM
  • In my case there is no chance of passing Unicode values.
    Tuesday, January 29, 2013 5:34 AM
  • The question is not what are you passing but what is expected by the function. Is it expecting char* or wchar_t* as parameter?

    Another thing which might be of interest is the signature of the SetPathName. Is it the same as that SetFileLogPathName method?

    Are you sure you're using the correct calling convention? Default is StdCall. You might try using CallingConvention.Cdecl for your DllImport.

    Tuesday, January 29, 2013 9:00 AM