473,776 Members | 2,210 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Passing char from C to C# using dll

29 New Member
hello ,

I have written these codes :

Mydll file :

Mydll.h

Expand|Select|Wrap|Line Numbers
  1. #ifndef MYDLL_H
  2. #define MYDLL_H
  3.  
  4. #define EXPORT __declspec(dllexport)
  5.  
  6. extern "C" void EXPORT __stdcall set(char c);
  7. extern "C" char EXPORT __stdcall get(void);
  8.  
  9. #end
  10.  

Mydll.cpp

Expand|Select|Wrap|Line Numbers
  1. #include "MyDll.h"
  2. #include <windows.h>
  3.  
  4. extern "C" static char o ;
  5.  
  6. void __stdcall set(char c)
  7. { o = c; }
  8.  
  9. char __stdcall get(void)
  10. { return o; }
  11.  
  12. BOOL WINAPI DllMain(HANDLE hModule,DWORD dwReason,LPVOID lpReserved)
  13. { return TRUE; }
  14.  
exports.def

Expand|Select|Wrap|Line Numbers
  1. LIBRARY    "MyDll"
  2. EXPORTS
  3.         set @1
  4.         get @2
  5.  
My C# code :

Expand|Select|Wrap|Line Numbers
  1.  
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6.  
  7. namespace Csharp
  8. {
  9.     class Program
  10.     {
  11.         [DllImport("Mydll.dll")]
  12.         [return: MarshalAs(UnmanagedType.I1)]
  13.         public static extern char get();
  14.  
  15.         [DllImport("Mydll.dll")]
  16.         public static extern void set([MarshalAs(UnmanagedType.I1)]char value);
  17.  
  18.         static void Main(string[] args)
  19.         {
  20.  
  21.             Console.WriteLine(get());
  22.             Console.Read();
  23.  
  24.         }
  25.     }
  26. }
  27.  
  28.  
My C code :

Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<windows.h>
  3. main(){
  4. HANDLE ldll;
  5. typedef void (__stdcall *set)(char f);
  6. typedef char (__stdcall *get)(void);
  7. char k = 's' ;
  8. set Set;
  9. get Get;
  10. ldll = LoadLibrary(TEXT("MyDll.dll"));
  11. Set = (set)GetProcAddress(ldll, "set");
  12. Get = (get)GetProcAddress(ldll, "get");
  13. Set(k);
  14.  
  15. printf("%c",Get());
  16.  
  17.  
  18.  
  19. }
  20.  
  21.  

i get no errors but i get no result also !!!

when i call set and get in C program only i can see the char .
the same when i call them in C#.

but when i call set in C and get in C# so i can pass the char i get no output !!

i can't see the char !!
Jan 3 '10 #1
4 5070
Banfa
9,065 Recognized Expert Moderator Expert
That is because that wont work. DLLs do not share memory between programs, each program that uses a DLL has a separate instance of the memory used by the DLL in its own address space. It has to work like this in order to allow a misbehaving program to be terminated by the OS and for the OS to be able to release all its resources and has been like this since the switch from WIN16 to WIN32 (in WIN16 a DLL actual got its own address space and the data in a DLL was shared between all programs that used it).

If you want to pass a char or any data from a C program to a C# program you will need to find an alternate method. I guess that pipes might work.
Jan 3 '10 #2
Amera
29 New Member
i can use C++ manage class right ?

i did it in the dll

but i couldn't call it from C#

the class exported from dll can't be known in C# !!!

i get the error :

The type or namespace name 'Adder' could not be found (are you missing a using directive or an assembly reference?)

this is my dll code after i added the exported class :

Mydll.h :

Expand|Select|Wrap|Line Numbers
  1.  
  2. #undef AFX_DATA
  3. #define AFX_DATA AFX_EXT_DATA
  4.  
  5. #ifndef MYDLL_H
  6. #define MYDLL_H
  7.  
  8. #define EXPORT __declspec(dllexport)
  9.  
  10. extern "C" void EXPORT __stdcall set(char c);
  11.  
  12. class __declspec(dllexport) Adder
  13. {
  14.     public:
  15.         Adder(){;};
  16.         ~Adder(){;};
  17.         char get(void);
  18. };
  19.  
  20. #endif
  21.  
  22.  
  23. #undef AFX_DATA
  24. #define AFX_DATA
  25.  
  26.  

Mydll.cpp :

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include "MyDll.h"
  3. #include <windows.h>
  4.  
  5. #using <mscorlib.dll>
  6. using namespace System;
  7. using namespace System::Collections;
  8.  
  9. extern "C" static char o ;
  10.  
  11. #pragma unmanaged directive
  12. char Adder::get(void)
  13. {
  14.     return o;
  15. }
  16.  
  17.  
  18. #pragma unmanaged directive
  19. void __stdcall set(char c)
  20. { o = c; }
  21.  
  22.  
  23. #pragma unmanaged directive
  24. BOOL WINAPI DllMain(HANDLE hModule,DWORD dwReason,LPVOID lpReserved)
  25. { return TRUE; }
  26.  
and this is C# where i called the class above :

Expand|Select|Wrap|Line Numbers
  1.  
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6.  
  7. namespace Csharp
  8. {
  9.     class Program
  10.     {
  11.         [DllImport("Mydll.dll")]
  12.         [return: MarshalAs(UnmanagedType.I1)]
  13.         public static extern char get();
  14.  
  15.         [DllImport("Mydll.dll")]
  16.         public static extern void set([MarshalAs(UnmanagedType.I1)]char value);
  17.  
  18.         static void Main(string[] args)
  19.         {
  20.             Adder a = new Adder();
  21.             Console.WriteLine(a.get());
  22.             Console.WriteLine();
  23.             Console.Read();
  24.  
  25.         }
  26.     }
  27. }
  28.  
  29.  
  30.  
  31.  
Jan 4 '10 #3
Banfa
9,065 Recognized Expert Moderator Expert
I am not that familiar with .NET/CLR programming. However the separation of processes virtual memory maps is a feature provided by the OS and should not as such be affected by the language you choose to implement your programs in.

That is the is no special magic bullet language that allows 2 different processes to suddenly be able to share memory. The .NET framework may well provide ways round this, in fact the WIN32 API provides ways round this such as memory mapped files.

It is not possible to transfer values between programs via a shared library on Windows. .NET may provide a way round this but I am not familiar enough with .NET to know but it would be a .NET implemented thing not something implemented natively.
Jan 4 '10 #4
weaknessforcats
9,208 Recognized Expert Moderator Expert
The class Adder is a C++ class. It has been compiled as C++ and is not accessible from C#.

You will need towrite a C++ function you can call from C#. The C++ function will do the work in C++ and pass the result (if necessary) back to C#.

This should akll be explained in the MSDN Interoperabilit y topics between C# and C++.
Jan 4 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

8
3969
by: Alex Vinokur | last post by:
Various forms of argument passing ================================= C/C++ Performance Tests ======================= Using C/C++ Program Perfometer http://sourceforge.net/projects/cpp-perfometer http://alexvn.freeservers.com/s1/perfometer.html
58
10181
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
17
2274
by: BlindHorse | last post by:
Help!!! I need someone to tell me why I am getting the err msg error C2440: '=' : cannot convert from 'char *' to 'char' //==================== #include <iostream>
3
2284
by: Steven Taylor | last post by:
Hope someone can assist. I'm trying to answer a book question. I'm going around in circles in relation to 'pointer-to-char'. Object : A short program is to be created, which involves a structore and one member element is a char array. A function is to be created that passes the structure as a reference, along with the 'pointer-to-char'. The function is to assign the passed-in 'pointer-to-char' to the referenced (passed-in)...
1
3269
by: Shawn | last post by:
As if it won't be clear enough from my code, I'm pretty new to C programming. This code is being compiled with an ANSI-C compatible compiler for a microcontroller. That part, I believe, will be irrelavent. My syntax is surely where I am going wrong. I'd like to be able to call this routine to read different values from another device. This routine would be called quite simply as follows: void main() {
3
3495
by: ZMan | last post by:
The following code won't compile with gcc version 3.4.2 (mingw-special). How come? Error: cannot convert `char (*)' to `char**' /**********************************************************/ #include <cstdio> #define MAX_WORD_LEN 80 #define MAX_SIZE 1000
3
1430
by: Amit_Basnak | last post by:
Dear friends I have to pass the objec of a class which is a part of afunction in thefunction call. my code looks like this now #include <iostream.h> #include <waspc/common.h> #include <waspc/runtime/Runtime.h> #include "WFWuList.h"
11
7197
by: Bob Yang | last post by:
Hi, I have this in C++ and I like to call it from c# to get the value but I fail. it will be good if you can give me some information. I tried it in VB.net it works but I use almost the same way as VB in C# but it doens't work. c++: (csp2.dll) NoMangle long DLL_IMPORT_EXPORT csp2TimeStamp2Str(unsigned char *Stamp, char *value, long nMaxLength);
6
3884
by: Andy Baker | last post by:
I am attempting to write a .NET wrapper for a C++ DLL file, but am having problems with passing strings as parameters. How should I be writing my C# function call when the C header file is definined as taking a char * as an argument? For example the C++ header says SDCERR GetCurrentConfig(DWORD *num, char *name); I am using Uint for the *num parameter, which returns the correct value but for *name, I always get back a string of 6 squares....
13
3207
by: Andy Baker | last post by:
I am attempting to write a .NET wrapper in C# for an SDK that has been supplied as a .LIB file and a .h header file. I have got most of the functions to work but am really struggling with the functions that require a structure to be passed to them. The function declaration in the .h file is of the form: SDCERR GetConfig(char *name, SDCConfig *cfg); where SDCConfig is a structure defined in the .h file. I am not much of a C (or C#)...
0
9625
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9459
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10056
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9920
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8948
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7467
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6721
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5489
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2857
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.