How to create a C# project with C++ library?

This post is written with help from many online resources and professional experience.

The main motivation behind using a C++ library for a C# code is code re-usability. I personally found it really hard to find a good resource on the net to create a C# project with C++ code.

Sample project – https://github.com/ashwinrs/TweetBank

Here are the steps involved in visual studio –

Adding the C++ project to VS-

First step is to get your C++ native code in to visual studio. File-> New -> Project -> Visual C++ -> Empty Project -> Ok . After this you can add existing code to your newly created project.  In my code example the native C++ project is called “TweetBank”

  1. Right click the TweetBank project. Properties->General->ConfigurationType->StaticLibrary
  2. When you build it a lib directory will be created under “\TweetBank\Debug\TweetBank.lib”

Adding the CLR project to VS-

The CLR project acts like a bridge between your C++ code and C# code. File-> Add -> New Project -> Visual C++ -> CLR ->Empty Project

In my code example, the project and the class is named “TweetBankCLR”.

  1. Right click the TweetBankCLR project and click properties. C/C++->General->Additional Include Directories-> <Add TweetBankCore’s project directory>
  2. In properties go to Linker -> Input -> Additional Dependencies -> “TweetBank.lib”
  3. In propertied go to Linker -> general -> Additional Library Directories -> “E:\Apps\Dropbox\Code\vs\TweetBank\Debug”
  4. Right click the TweetBankCLR project. Properties->General->ConfigurationType->dll (This will create a DLL)
  5. Add reference to native project. Right click TweetBankCLR Add- > Reference -> Projects/solutions -> TweetBank

Adding the C# project to VS-

I will be creating a WPF project here. File-> Add -> New Project -> Visual C# -> Empty WPF Application. In my code example this project is named “TweetBankWPF”.

  1. Right click the TweetBankWPF and click “Set as Startup Project”
  2. Add reference to CLR project. Right click TweetBankWPF Add- > Reference -> Projects/solutions -> TweetBankCLR
  3. Right click and build TweetBankCLR. This should resolve any unresolved references from you C# code.
  4. Build TweetBankWPF. Tada!

More helpful links –

  1. http://stackoverflow.com/questions/19163839/how-to-access-class-in-c-cli-from-c
  2. http://stackoverflow.com/questions/10223186/c-cli-wrapper-for-native-c-to-use-as-reference-in-c-sharp
  3. For more info on how different data need to be exchanged between C# and C++ – http://www.codeproject.com/Articles/19354/Quick-C-CLI-Learn-C-CLI-in-less-than-minutes

 

 

 

 

How to create a C# project with C++ library?

Compilation error – error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before

If you run into following error “FILENAME.h:135: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before” during compilations.
The error is pretty descriptive. But in my case there were all expected symbols but it still was giving that error.
After some time with some help of  a colleague, figured out that I was trying to include a .h file in a .c file which was actually meant for a .cxx/.cpp file. So if your header file has classes defined in it, it is meant for a c++ file and not a c file. It sounds really simple but it did stump me for sometime 🙂
Compilation error – error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before

C Notes

1. when #define is used, we are replacing a number with a string.
Ex. #define NUM 5
So, we cannot use NUM– or NUM++, since NUM is not a memory location / register to be incremented or decremented.

2. When accessing an array with a pointer, adding 1 to the pointer actually increments the pointer by 4(depending on the compiler being used).
Ex.
int arr[5] = {1,4,1,5,1};
//To access the last element of the array =
printf("%d\n",*(arr+4)); // is CORRECT
printf("%d\n",*(arr+(sizeof(int)*4)); //is WRONG

Summarizing: When you add a value to a pointer it automatically increments the number of bytes the data type is allocated. Here, by adding 4 the pointer is actually incremented by 16.

3. By default character is signed(so are other data types). It varies from -128(0x80) to 127(0x79). If we make the character unsigned – the values range from (0 to 255).

4. How to find if a system is little endian or Big endian
In case of a little endian(all intel chips), the least significant byte is stored in the first memory address. But in case of Big Endian, the most significant byte is stored in the first memory location.
void getEndian(){
short int word = 1;
char *byte = (char *) &word;
printf("%s",(byte[0] ? "Little endian" : "Big Endian"));
}

5. Segmentation Fault
A segmentation fault (often shortened to segfault), bus error or access violation is generally an attempt to access memory that the CPU cannot physically address. It occurs when the hardware notifies an operating system about a memory access violation. The OS kernel then sends a signal to the process which caused the exception. By default, the process receiving the signal dumps core and terminates
Source – Wikipedia

6.When we increment an unsigned data type which is holding the maximum value of that data type, it will become 0
Example :

unsigned long ul = ULONG_MAX;
ul++;
printf(“%d”,ul); // will print 0

7. Pointers – link

8. Structures – inside a struct, if there is an integer and a char, the size of the struct will be 8 and not 5. This is because the compiler allocates more memory to make it aligned. If a struct has a single char, the size will be 1.

struct mystruct{

int i;

char c;

}; //size is 8 and not 5

C Notes

C : Integer overflow

I once had a piece of code which tried to compute the number of bytes in a buffer with the expression (k * 1024) where k was an int representing the number of kilobytes I wanted. Unfortunately this was on a machine where int happened to be 16 bits. Since k and 1024 were both int, there was no promotion. For values of k >= 32, the product was too big to fit in the 16 bit int resulting in an overflow. The compiler can do whatever it wants in overflow situations — typically the high order bits just vanish. One way to fix the code was to rewrite it as (k * 1024L) — the long constant forced the promotion of the int. This was not a fun bug to track down — the expression sure looked reasonable in the source code. Only stepping past the key line in the debugger showed the overflow problem. “Professional Programmer’s Language.” This example also demonstrates the way that C only promotes based on the types in an expression. The compiler does not consider the values 32 or 1024 to realize that the operation will overflow (in general, the values don’t exist until run time anyway). The compiler just looks at the compile time types, int and int in this case, and thinks everything is fine. 

 

courtesy – Stanford

C : Integer overflow

C : What happens when u add a char and an integer?

The integral types may be mixed together in arithmetic expressions since they are all basically just integers with variation in their width. For example, char and int can be combined in arithmetic expressions such as (‘b’ + 5). How does the compiler deal with the different widths present in such an expression? In such a case, the compiler “promotes” the smaller type (char) to be the same size as the larger type (int) before combining the values. Promotions are determined at compile time based purely on the types of the values in the expressions. Promotions do not lose information — they always convert from a type to compatible, larger type to avoid losing information. 

C : What happens when u add a char and an integer?