Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to pass .net (C#) string to unmanaged C++ dll?

How to pass .net (C#) string to unmanaged C++ dll?

Scheduled Pinned Locked Moved C#
csharphelpc++performancetutorial
13 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    Tesic Goran
    wrote on last edited by
    #1

    Hi, We have an issue - how to pass .net (C#) string to unmanaged C++ dll? We tried something, but this error came up: "An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Does anybody know how to do this? We need the code sample. Thank you in advance. Goran

    L D 2 Replies Last reply
    0
    • T Tesic Goran

      Hi, We have an issue - how to pass .net (C#) string to unmanaged C++ dll? We tried something, but this error came up: "An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Does anybody know how to do this? We need the code sample. Thank you in advance. Goran

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      Should be no problem. A managed string can be passed to a native char* (read-only) in a straightforward way; for a writeable char*, you need a StringBuilder. See this little article[^]. :)

      Luc Pattyn [My Articles] Nil Volentibus Arduum

      The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
      Please use <PRE> tags for code snippets, they improve readability.
      CP Vanity has been updated to V2.3

      T 1 Reply Last reply
      0
      • T Tesic Goran

        Hi, We have an issue - how to pass .net (C#) string to unmanaged C++ dll? We tried something, but this error came up: "An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Does anybody know how to do this? We need the code sample. Thank you in advance. Goran

        D Offline
        D Offline
        DaveyM69
        wrote on last edited by
        #3

        As Luc Says, it shoul be no problem. To help any further we would need to see the unmanaged function signature.

        Dave
        Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

        T 1 Reply Last reply
        0
        • L Luc Pattyn

          Should be no problem. A managed string can be passed to a native char* (read-only) in a straightforward way; for a writeable char*, you need a StringBuilder. See this little article[^]. :)

          Luc Pattyn [My Articles] Nil Volentibus Arduum

          The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
          Please use <PRE> tags for code snippets, they improve readability.
          CP Vanity has been updated to V2.3

          T Offline
          T Offline
          Tesic Goran
          wrote on last edited by
          #4

          Thank you. I've just tried it, but the same error came up. Our C# code looks as follows:

          \[ComVisible(true)\]
          \[InterfaceType(ComInterfaceType.InterfaceIsDual)\]
          \[Guid("F4100FB3-75C5-4C4F-8034-9B836598DD1E")\]
          public interface IDecoder
          {
              \[return: MarshalAs(UnmanagedType.BStr)\]
              StringBuilder Decode(\[MarshalAs(UnmanagedType.BStr)\] ref string encodedString);
          
          public class UfoDecoder : IDecoder
          {
              public StringBuilder Decode(ref string encodedString)
              {
                  byte\[\] dec64 = Base64Decode(encodedString);
                  byte\[\] unzipped = CompressionUtility.Decompress(dec64);
          
                  return BinToXml(unzipped);
              }
          

          And our C++ code looks as follows:

          extern "C" __declspec(dllexport) void decode(char *encString, char *answer )
          {

          // Initialize COM.
              HRESULT hr = CoInitialize(NULL);
          IDecoderPtr pIDec(\_\_uuidof(UfoDecoder));
          
              BSTR k1 = bstr\_t(encString);
          BSTR k2 = bstr\_t(answer);
          
          pIDec -> Decode(&k1, &k2);
          

          The error comes up on calling last line in C++ block.

          modified on Monday, May 30, 2011 5:05 AM

          L 1 Reply Last reply
          0
          • D DaveyM69

            As Luc Says, it shoul be no problem. To help any further we would need to see the unmanaged function signature.

            Dave
            Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
            BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

            T Offline
            T Offline
            Tesic Goran
            wrote on last edited by
            #5

            Yes. I've just posted it up there.

            1 Reply Last reply
            0
            • T Tesic Goran

              Thank you. I've just tried it, but the same error came up. Our C# code looks as follows:

              \[ComVisible(true)\]
              \[InterfaceType(ComInterfaceType.InterfaceIsDual)\]
              \[Guid("F4100FB3-75C5-4C4F-8034-9B836598DD1E")\]
              public interface IDecoder
              {
                  \[return: MarshalAs(UnmanagedType.BStr)\]
                  StringBuilder Decode(\[MarshalAs(UnmanagedType.BStr)\] ref string encodedString);
              
              public class UfoDecoder : IDecoder
              {
                  public StringBuilder Decode(ref string encodedString)
                  {
                      byte\[\] dec64 = Base64Decode(encodedString);
                      byte\[\] unzipped = CompressionUtility.Decompress(dec64);
              
                      return BinToXml(unzipped);
                  }
              

              And our C++ code looks as follows:

              extern "C" __declspec(dllexport) void decode(char *encString, char *answer )
              {

              // Initialize COM.
                  HRESULT hr = CoInitialize(NULL);
              IDecoderPtr pIDec(\_\_uuidof(UfoDecoder));
              
                  BSTR k1 = bstr\_t(encString);
              BSTR k2 = bstr\_t(answer);
              
              pIDec -> Decode(&k1, &k2);
              

              The error comes up on calling last line in C++ block.

              modified on Monday, May 30, 2011 5:05 AM

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #6

              get rid of the ref keyword, objects always get passed by reference, your native code will get a pointer without using ref. FWIW: With ref, it would be a char**. [ADDED] On a second read, I don't understand your native code at all. It seems to me the decode() function isn't relevant. All that matters is Decode(), of which you didn't show the actual signature. However your prototype suggests it returns a StringBuilder (bad idea, that is a managed type, no native function returns managed types automatically), and yet your decode() just ignores the return value!?!? If you need more help, please show the declaration of the native Decode() function. If it doesn't require BSTR (say it just takes two char*, then things should be simple). [/ADDED] :)

              Luc Pattyn [My Articles] Nil Volentibus Arduum

              The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
              Please use <PRE> tags for code snippets, they improve readability.
              CP Vanity has been updated to V2.3

              modified on Monday, May 30, 2011 5:38 AM

              T 1 Reply Last reply
              0
              • L Luc Pattyn

                get rid of the ref keyword, objects always get passed by reference, your native code will get a pointer without using ref. FWIW: With ref, it would be a char**. [ADDED] On a second read, I don't understand your native code at all. It seems to me the decode() function isn't relevant. All that matters is Decode(), of which you didn't show the actual signature. However your prototype suggests it returns a StringBuilder (bad idea, that is a managed type, no native function returns managed types automatically), and yet your decode() just ignores the return value!?!? If you need more help, please show the declaration of the native Decode() function. If it doesn't require BSTR (say it just takes two char*, then things should be simple). [/ADDED] :)

                Luc Pattyn [My Articles] Nil Volentibus Arduum

                The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
                Please use <PRE> tags for code snippets, they improve readability.
                CP Vanity has been updated to V2.3

                modified on Monday, May 30, 2011 5:38 AM

                T Offline
                T Offline
                Tesic Goran
                wrote on last edited by
                #7

                Do you mean on this:

                \[ComVisible(true)\]
                \[InterfaceType(ComInterfaceType.InterfaceIsDual)\]
                \[Guid("F4100FB3-75C5-4C4F-8034-9B836598DD1E")\]
                public interface IDecoder
                {
                    \[return: MarshalAs(UnmanagedType.BStr)\]
                    StringBuilder Decode(\[MarshalAs(UnmanagedType.BStr)\] string encodedString);
                
                public class UfoDecoder : IDecoder
                {
                    public StringBuilder Decode(string encodedString)
                    {
                        byte\[\] dec64 = Base64Decode(encodedString);
                        byte\[\] unzipped = CompressionUtility.Decompress(dec64);
                
                        return BinToXml(unzipped);
                    }
                

                If so, I have the same error.

                L 1 Reply Last reply
                0
                • T Tesic Goran

                  Do you mean on this:

                  \[ComVisible(true)\]
                  \[InterfaceType(ComInterfaceType.InterfaceIsDual)\]
                  \[Guid("F4100FB3-75C5-4C4F-8034-9B836598DD1E")\]
                  public interface IDecoder
                  {
                      \[return: MarshalAs(UnmanagedType.BStr)\]
                      StringBuilder Decode(\[MarshalAs(UnmanagedType.BStr)\] string encodedString);
                  
                  public class UfoDecoder : IDecoder
                  {
                      public StringBuilder Decode(string encodedString)
                      {
                          byte\[\] dec64 = Base64Decode(encodedString);
                          byte\[\] unzipped = CompressionUtility.Decompress(dec64);
                  
                          return BinToXml(unzipped);
                      }
                  

                  If so, I have the same error.

                  L Offline
                  L Offline
                  Luc Pattyn
                  wrote on last edited by
                  #8

                  sorry, we were both typing at the same time. I expanded my earlier reply. :)

                  Luc Pattyn [My Articles] Nil Volentibus Arduum

                  The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
                  Please use <PRE> tags for code snippets, they improve readability.
                  CP Vanity has been updated to V2.3

                  T 1 Reply Last reply
                  0
                  • L Luc Pattyn

                    sorry, we were both typing at the same time. I expanded my earlier reply. :)

                    Luc Pattyn [My Articles] Nil Volentibus Arduum

                    The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
                    Please use <PRE> tags for code snippets, they improve readability.
                    CP Vanity has been updated to V2.3

                    T Offline
                    T Offline
                    Tesic Goran
                    wrote on last edited by
                    #9

                    Ok. The whole code is here:

                    extern "C" __declspec(dllexport) void decode(char *encString, char *answer )
                    {
                    // Initialize COM.
                    HRESULT hr = CoInitialize(NULL);
                    IDecoderPtr pIDec(__uuidof(UfoDecoder));

                    BSTR k1 = bstr\_t(encString);
                    BSTR k2 = bstr\_t(answer);
                    
                    pIDec->Decode(&k1,&k2);
                    
                    SysFreeString(k1);
                    SysFreeString(k2);
                    

                    }

                    int _tmain(int argc, _TCHAR* argv[])
                    {
                    char *xml = (char*)malloc(5000000*sizeof(char));
                    char* str = "Some encoded string";
                    int length = strlen(str);

                    decode(str, xml);
                    
                    printf("Decoded = %s",xml);
                    
                    int vol = strlen(xml);
                    return 0;
                    

                    }

                    \[ComVisible(true)\]
                    \[InterfaceType(ComInterfaceType.InterfaceIsDual)\]
                    \[Guid("F4100FB3-75C5-4C4F-8034-9B836598DD1E")\]
                    public interface IDecoder
                    {
                        \[return: MarshalAs(UnmanagedType.BStr)\]
                        string Decode(\[MarshalAs(UnmanagedType.BStr)\] ref string encodedString);
                    
                    
                    \[ComVisible(true)\]
                    \[Guid("85F2DFFB-5655-40DD-A779-94388A2773DC")\]
                    \[ProgId("UfoDecodeWrapper.UfoDecoder")\]
                    \[ClassInterface(ClassInterfaceType.None)\]
                    \[ComDefaultInterface(typeof(IDecoder))\]
                    public class UfoDecoder : IDecoder
                    {
                        public string Decode(ref string encodedString)
                        {
                            byte\[\] dec64 = Base64Decode(encodedString);
                            byte\[\] unzipped = CompressionUtility.Decompress(dec64);
                    
                            return BinToXml(unzipped);
                        }
                    

                    [ADDED] If str variable in _tmain function in this line: char* str = "Some encoded string"; is not so long we're getting Xml. But, if str is very long, the error comes up. [/ADDED]

                    modified on Monday, May 30, 2011 6:22 AM

                    L M 2 Replies Last reply
                    0
                    • T Tesic Goran

                      Ok. The whole code is here:

                      extern "C" __declspec(dllexport) void decode(char *encString, char *answer )
                      {
                      // Initialize COM.
                      HRESULT hr = CoInitialize(NULL);
                      IDecoderPtr pIDec(__uuidof(UfoDecoder));

                      BSTR k1 = bstr\_t(encString);
                      BSTR k2 = bstr\_t(answer);
                      
                      pIDec->Decode(&k1,&k2);
                      
                      SysFreeString(k1);
                      SysFreeString(k2);
                      

                      }

                      int _tmain(int argc, _TCHAR* argv[])
                      {
                      char *xml = (char*)malloc(5000000*sizeof(char));
                      char* str = "Some encoded string";
                      int length = strlen(str);

                      decode(str, xml);
                      
                      printf("Decoded = %s",xml);
                      
                      int vol = strlen(xml);
                      return 0;
                      

                      }

                      \[ComVisible(true)\]
                      \[InterfaceType(ComInterfaceType.InterfaceIsDual)\]
                      \[Guid("F4100FB3-75C5-4C4F-8034-9B836598DD1E")\]
                      public interface IDecoder
                      {
                          \[return: MarshalAs(UnmanagedType.BStr)\]
                          string Decode(\[MarshalAs(UnmanagedType.BStr)\] ref string encodedString);
                      
                      
                      \[ComVisible(true)\]
                      \[Guid("85F2DFFB-5655-40DD-A779-94388A2773DC")\]
                      \[ProgId("UfoDecodeWrapper.UfoDecoder")\]
                      \[ClassInterface(ClassInterfaceType.None)\]
                      \[ComDefaultInterface(typeof(IDecoder))\]
                      public class UfoDecoder : IDecoder
                      {
                          public string Decode(ref string encodedString)
                          {
                              byte\[\] dec64 = Base64Decode(encodedString);
                              byte\[\] unzipped = CompressionUtility.Decompress(dec64);
                      
                              return BinToXml(unzipped);
                          }
                      

                      [ADDED] If str variable in _tmain function in this line: char* str = "Some encoded string"; is not so long we're getting Xml. But, if str is very long, the error comes up. [/ADDED]

                      modified on Monday, May 30, 2011 6:22 AM

                      L Offline
                      L Offline
                      Luc Pattyn
                      wrote on last edited by
                      #10

                      Sorry, I give up. It is all just too confusing for me. I now think you have native code calling managed code, not the other way around. :doh:

                      Luc Pattyn [My Articles] Nil Volentibus Arduum

                      The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
                      Please use <PRE> tags for code snippets, they improve readability.
                      CP Vanity has been updated to V2.3

                      modified on Friday, June 10, 2011 8:47 PM

                      T 2 Replies Last reply
                      0
                      • L Luc Pattyn

                        Sorry, I give up. It is all just too confusing for me. I now think you have native code calling managed code, not the other way around. :doh:

                        Luc Pattyn [My Articles] Nil Volentibus Arduum

                        The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
                        Please use <PRE> tags for code snippets, they improve readability.
                        CP Vanity has been updated to V2.3

                        modified on Friday, June 10, 2011 8:47 PM

                        T Offline
                        T Offline
                        Tesic Goran
                        wrote on last edited by
                        #11

                        I've added some explanation up there: [ADDED] If str variable in _tmain function in this line: char* str = "Some encoded string"; is not so long we're getting Xml. But, if str is very long, the error comes up. [/ADDED]

                        1 Reply Last reply
                        0
                        • L Luc Pattyn

                          Sorry, I give up. It is all just too confusing for me. I now think you have native code calling managed code, not the other way around. :doh:

                          Luc Pattyn [My Articles] Nil Volentibus Arduum

                          The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
                          Please use <PRE> tags for code snippets, they improve readability.
                          CP Vanity has been updated to V2.3

                          modified on Friday, June 10, 2011 8:47 PM

                          T Offline
                          T Offline
                          Tesic Goran
                          wrote on last edited by
                          #12

                          "decode" function is relevant because it's placed in this function:

                          int _tmain(int argc, _TCHAR* argv[])
                          {
                          char *xml = (char*)malloc(5000000*sizeof(char));
                          char* str = "Some encoded string";
                          int length = strlen(str);

                          decode(str, xml);
                          
                          printf("Decoded = %s",xml);
                          
                          int vol = strlen(xml);
                          return 0;
                          

                          }

                          1 Reply Last reply
                          0
                          • T Tesic Goran

                            Ok. The whole code is here:

                            extern "C" __declspec(dllexport) void decode(char *encString, char *answer )
                            {
                            // Initialize COM.
                            HRESULT hr = CoInitialize(NULL);
                            IDecoderPtr pIDec(__uuidof(UfoDecoder));

                            BSTR k1 = bstr\_t(encString);
                            BSTR k2 = bstr\_t(answer);
                            
                            pIDec->Decode(&k1,&k2);
                            
                            SysFreeString(k1);
                            SysFreeString(k2);
                            

                            }

                            int _tmain(int argc, _TCHAR* argv[])
                            {
                            char *xml = (char*)malloc(5000000*sizeof(char));
                            char* str = "Some encoded string";
                            int length = strlen(str);

                            decode(str, xml);
                            
                            printf("Decoded = %s",xml);
                            
                            int vol = strlen(xml);
                            return 0;
                            

                            }

                            \[ComVisible(true)\]
                            \[InterfaceType(ComInterfaceType.InterfaceIsDual)\]
                            \[Guid("F4100FB3-75C5-4C4F-8034-9B836598DD1E")\]
                            public interface IDecoder
                            {
                                \[return: MarshalAs(UnmanagedType.BStr)\]
                                string Decode(\[MarshalAs(UnmanagedType.BStr)\] ref string encodedString);
                            
                            
                            \[ComVisible(true)\]
                            \[Guid("85F2DFFB-5655-40DD-A779-94388A2773DC")\]
                            \[ProgId("UfoDecodeWrapper.UfoDecoder")\]
                            \[ClassInterface(ClassInterfaceType.None)\]
                            \[ComDefaultInterface(typeof(IDecoder))\]
                            public class UfoDecoder : IDecoder
                            {
                                public string Decode(ref string encodedString)
                                {
                                    byte\[\] dec64 = Base64Decode(encodedString);
                                    byte\[\] unzipped = CompressionUtility.Decompress(dec64);
                            
                                    return BinToXml(unzipped);
                                }
                            

                            [ADDED] If str variable in _tmain function in this line: char* str = "Some encoded string"; is not so long we're getting Xml. But, if str is very long, the error comes up. [/ADDED]

                            modified on Monday, May 30, 2011 6:22 AM

                            M Offline
                            M Offline
                            MicroVirus
                            wrote on last edited by
                            #13

                            Please avoid using things like:

                            char* str = "A string literal here";

                            If you define it this way, it should be defined as a const char*. If it needs to be editted, define it as a char array with a large enough size. Also, why are you calling pIDec->Decode(&k1,&k2);. Why not just pIDec->Decode(k1,k2);? And then... why are you defining Decode as a function with one parameter and yet calling it with two parameters?

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups