Results 1 to 19 of 19

Thread: [RESOLVED] Difference between C and C++ mode / call function from VB

  1. #1

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Resolved [RESOLVED] Difference between C and C++ mode / call function from VB

    I want to develop a function in C/C++ to take a large string and search for keywords - and calling this function from VB.Net.

    First - I was curious what the difference is between compiling in C and C++ modes?

    Second - having never written a function in C/C++ - how would I code up the parameters for passing an array of "keywords" and a large "string" of text from VB.Net (using VS 2010).

    Thanks!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Difference between C and C++ mode / call function from VB

    Compiling in "C mode" (With the /TC switch) will treat all source code as C code, which will give you syntax errors if you write any C++ code in your source files. Given that C and C++ are so similar, I'm not sure exactly of the differences in how the compiler compiles when using the /TC (C) vs the /TP (C++) flag. A c++ compiler should be able to compile C code. Perhaps different assumptions can be made when optimizing C versus C++ code? Not sure.

    I just tried this and it worked alright.
    C code:
    Code:
    __declspec(dllexport) int firstIndexOfKeyword(char *str, char **keywords, int nKeywords) {
    	int i, j, k;
    	int keywordlen;
    	int len = strlen(str);
    
    	for(k = 0; k < nKeywords; k++)
    	{
    		keywordlen = strlen(keywords[k]);
    
    		for(i = 0; i <= len - keywordlen; i++)
    		{
    			for(j = 0; j < keywordlen; j++)
    			{
    				if(keywords[k][j] != str[i + j])
    					j = keywordlen+1;
    			}
    
    			if(j == keywordlen)
    				return i;
    		}
    	}
    
    	return -1;
    }
    And invoked from VB like this:
    Code:
        <System.Runtime.InteropServices.DllImport("C:\Users\emil\Documents\visual studio 2010\Projects\CDll\Debug\CDll.dll", CallingConvention:=Runtime.InteropServices.CallingConvention.Cdecl)> _
        Public Function firstIndexOfKeyword(ByVal s As String, ByVal substr As String(), ByVal substrLength As Integer) As Integer
        End Function
    
        Sub Main()
            Dim text As String = "i had fancy italian food for lunch"
            Dim keywords As String() = {"meh", "feh", "italian"}
            Dim index As Integer = firstIndexOfKeyword(text, keywords, keywords.Length)
            Console.WriteLine("Index: {0}", index)
        End Sub
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    Thank you - this is great!

    Question - I'm working on a solution in VS 2010 - all VB now - with 5 projects.

    I want to add a new project for this C/C++ stuff - do I make it a MFC DLL - a CLASS LIBRARY??
    Attached Images Attached Images  

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  4. #4
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Difference between C and C++ mode / call function from VB

    I have never used MFC so I'm not even sure..what it is!
    The class library project template uses C++/CLI, which may or may not be what you want!
    Another option is to create a Win32 Project, then choose DLL under Application Type in the wizard. This will give you a totally blank C/C++ project that compiles to a DLL.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  5. #5

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    I did that - seemed to work - made a lot of stuff...

    Check out this image - where do I put that function? Which of these files?

    Does it go in StringLibrary.cpp?

    Code:
    // StringLibrary.cpp : Defines the exported functions for the DLL application.
    //
    
    #include "stdafx.h"
    Attached Images Attached Images  

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  6. #6

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    Hey - I did put that code in the StringLibrary.cpp file - did a BUILD on the solution - and all seemed to be ok.

    Where do I put this code

    Code:
    <System.Runtime.InteropServices.DllImport("C:\Users\emil\Documents\visual studio 2010\Projects\CDll\Debug\CDll.dll", CallingConvention:=Runtime.InteropServices.CallingConvention.Cdecl)> _
        Public Function firstIndexOfKeyword(ByVal s As String, ByVal substr As String(), ByVal substrLength As Integer) As Integer
        End Function
    
        Sub Main()
            Dim text As String = "i had fancy italian food for lunch"
            Dim keywords As String() = {"meh", "feh", "italian"}
            Dim index As Integer = firstIndexOfKeyword(text, keywords, keywords.Length)
            Console.WriteLine("Index: {0}", index)
        End Sub
    I tried pasting that into the project that wants to call this new C/C++ function - and got this error

    'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method.

    ...and it would not allow me to add a REFERENCE to the STRINGLIBRARY project from the project that wants to call this C/C++ function.

    Also - I cannot find a .DLL in that DEBUG folder - I thought the BUILD for sure would have made that for me...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  7. #7

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    I found the .dll and also fixed the error by adding SHARED

    Public Shared Function firstIndexOfKeyword(ByVal s As String, ByVal substr As String(), ByVal substrLength As Integer) As Integer

    Is that the right thing to do? This C/C++ function is being called by several threads running in the other application.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  8. #8

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    Ran the code - got to that point - and in the immediate window I did

    Code:
    ?firstIndexOfKeyword("i had fancy italian food for lunch", {"meh", "feh", "italian"}, 3)
    {"An exception 'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException' occurred"}
        _HResult: -2146232832
        _message: "Error in the application."
        Data: {System.Collections.ListDictionaryInternal}
        HelpLink: Nothing
        HResult: -2146232832
        InnerException: Nothing
        IsTransient: False
        Message: "An exception 'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException' occurred"
        Source: "Microsoft.VisualStudio.Debugger.Runtime"
        StackTrace: "   at Microsoft.VisualStudio.Debugger.Runtime.Main.ThrowCrossThreadMessageException(String formatString)     at System.Windows.Forms.SafeNativeMethods.GetWindowTextLength(HandleRef hWnd)     at System.Windows.Forms.Control.get_WindowText()     at System.Windows.Forms.Form.get_WindowText()     at System.Windows.Forms.Control.get_Text()     at System.Windows.Forms.Form.get_Text()     at System.Windows.Forms.Form.ToString()"
        TargetSite: {Void ThrowCrossThreadMessageException(System.String)}
    And got a pop-up error about not finding the ENTRY point and this ugly cross threading error...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  9. #9
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Difference between C and C++ mode / call function from VB

    I'll have to look into why you are getting a cross threading error, but as to the entry point issue, Im afraid I failed to include that in my first post but you need to specify external C linkage by doing:

    Code:
    extern "C"
    {
      // Your method goes in here.
    }
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  10. #10

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    I started a new thread here in the VB .Net section of the forum...

    http://www.vbforums.com/showthread.php?t=676154

    I'll try that EXTERN C thing - that has something to do with MANAGLED NAMES - right?

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  11. #11
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Difference between C and C++ mode / call function from VB

    Quote Originally Posted by szlamany View Post
    I started a new thread here in the VB .Net section of the forum...

    I'll try that EXTERN C thing - that has something to do with MANAGLED NAMES - right?
    Yeah I'm not too read up on this but it defines how the compiler treats the code with regards to external linkage, and specifying C style linkage will not mangle the names.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  12. #12

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    Yeah - I got that far in my searching but the syntax is so new to me - and the solution files themselves - that I had no idea where to put anything...

    Tried to find a good book - all I left the book store with is a pocket guide - at least I can start to understand syntax and operators and such...

    I did see a comment that someone made that you should use C# if you want to work with lots of C/C++ functions. Is there truth to that?

    Is C# the C-style version of VB.Net?

    I'm going to be doing lots of multi-threading in all this as well...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  13. #13
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Difference between C and C++ mode / call function from VB

    Is C# the C-style version of VB.NET? I would say yes.

    But for the statement that you should use C# if you want to work with lots of C/C++ functions. I'm not too sure about that. I'm not sure if you gain anything to your C/C++ "skills" by using C#, other than the fact that you will have to get used to the semicolons! (That alone can be THE reason for some!)

    Other than that I think that there are so many other differences to get used to when doing C/C++ that the basic syntax is not one of the major ones (And thats about the only C/C++ knowledge you will gain from also doing C#).

    I hope that made any sense. I got confused while writing so I bet its also confusing to read
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  14. #14

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    Over the past year and a half I've become really fluent in javascript - so that type of object and function naming experience is strong. Is that already got me halfway to using C?

    Maybe it's time to abandon VB for C-style languages?

    Can I really do something like that after 30+ years?

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  15. #15

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    This is working now.

    btw - do I have to REBUILD it if I change the function? Seems that putting the EXTERN "C" in and RUNNING my whole solution (which starts 4 projects running at the same time) didn't work - I had to REBUILD. Do I REBUILD everytime I alter the function in some way??

    also - how do I break in the C++ function?

    It says no symbols have been loaded for this document.

    My path to the dll is in the debug folder

    Code:
        <System.Runtime.InteropServices.DllImport("D:\ACS Desktop\dcx\dcx\Debug\StringLibrary.dll", EntryPoint:="firstIndexOfKeyword", CallingConvention:=Runtime.InteropServices.CallingConvention.Cdecl)> _
        Public Shared Function firstIndexOfKeyword(ByVal s As String, ByVal substr As String(), ByVal substrLength As Integer) As Integer
        End Function
    Last edited by szlamany; Apr 4th, 2012 at 05:30 AM.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  16. #16
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Difference between C and C++ mode / call function from VB

    If you make any changes to a source file, that file will have to be recompiled. I believe msvc abandoned the use of Makefiles in c/c++ projects since a couple of versions back, in favor for msbuild project files, but they work essentially the same I believe. If a source file has changed since last time the project was compiled, it needs to be compiled, or else you will not be using the most recent build. By Building the project, it will only compile the source files that contains changes, and re-link the final executable. This way the entire c/c++ project does not need to be recompiled each time you make changes. If you Rebuild the project on the other hand, it will
    re-compile each of the source files regardless if they contain changes or not.

    As to the second question, I have never really tried to debug native code in a DLL that is invoked from .NET application, this looks like the way to do it.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  17. #17

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Difference between C and C++ mode / call function from VB

    Ok - I got the unmanaged code in the C++ function to work with the VS debugger.

    I had to go the the actual PROJECT I was calling the function from (not the overall SOLUTION - as I have several projects in this solution) - and under PROJECT PROPERTIES - DEBUG tab - check off ENABLE UNMANAGED CODE DEBUGGING.

    And I gotta say this really slowed down the startup of that particular project when I run the whole solution (4 projects fire up at once when I do a run). I can visually see the delay in that project starting.

    I will have to remember to toggle that option on and off based on whether I am coding in the C++ function...

    Thanks for all your help - I'm marking this thread resolved.

    Now I can do wicked fast string searching - at least I'm about to embark on that path!

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  18. #18

    Thread Starter
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: [RESOLVED] Difference between C and C++ mode / call function from VB

    btw - what do the "*" characters mean?

    Code:
    firstIndexOfKeyword(char *str, char **keywords, int nKeywords, int **markers)
    I figured that they mean "array" and wanted to pass in an integer array of MARKERS by reference...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  19. #19
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] Difference between C and C++ mode / call function from VB

    * deals with pointers. They have two uses: declaring pointer variables and dereferencing pointers.
    In this case, it declares str as a pointer-to-char, and keywords as a pointer-to-pointer-to-char.
    In the case of str, it will point to the beginning of the sequence of characters that makes up the string. And keywords will point to memory locations that in turn pointers to chars.

    And as for the other use of the asterisk, say that you want to find 'what' character str is "pointing" at. You'd do:

    Code:
    char firstChar = *str;
    You can then advance the pointer with ordinary arithmetics, and dereference it again to find the second character in the sequence:
    Code:
    char secondChar = *(++str);
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width