how to access class and its functions from another class - c#

This is my first major application using multiple classes. It is written in vb and I know about creating objects of the class and using that instance to call functions of the class. But how do I create an object with constructors to allow another program written in C# to access my classes and functions and accept things from the program.
Hope this makes sense.

Simply create a .NET class library and include that library as a reference inside the C# program. In .NET all libraries are .DLL files.
Once you do that the library will be available to C# with C# syntax.

You need to compile your VB classes into a class library (DLL) not an application.
From you C# application you need to add a reference to your newly compiled DLL. This DLL contains the classes and methods that you can instantiate and call from C#.
Once you've added a reference to the VB DLL from your C# assembly, you can access the VB classes (mostly) as though they were all in the same assembly. (I say mostly because access modifiers can change this, especially the 'internal' access modifier).

Dim myClassInstance As New MyClass()
edit: Ah, you want to define a class with constructors?
If that is the case, try this:
Public Class MyClass
Public Sub New(myNumber As Integer) 'Defines a constructor with an Integer as argument
End Sub
End Class

Related

Compiling to DLL

I have a couple of functions which I would like to add to DLL. I found this programming guide How to: Create and Use C# DLLs (C# Programming Guide). It's very short and looks like a really simple thing to do but I've noticed that each single function added to dll is enlosed in a separate file, separate class and functions are static. Is it always the case? What if I have a couple of overloaded functions, such as:
public void WaitForTheKey(object o = null) {}
public void WaitForTheKey(string message, bool addlines = true, int[] quantity = null) {}
private void _WaitForTheKey(string, bool, int[]) {}
Shall I put them in separate files like in the tutorial? Thanks.
EDIT.
If projects for DLL do not require separate classes and files, what would be the reason an author of the tutorial followed this theme?
Thanks
First of all you should keep you logic split by functionality. So all these methods you should keep in one class (in most cases it means one file).
It is very simple to create dll. If you use Visual Studio you should pick Class Library project type and then simply build it. As a result you will get dll file. Or use compiler directly from command prompt like it was shown in tutorial.
You are overthinking it; the tutorial is just an arbitrary example.
Simply structure the code in a way that makes sense, with as many or few classes as you like. Everything that is public in your assembly (classes, methods, properties, fields, events etc.) can be accessed by the consumer of the DLL.

C# classes exposed from javascript through Firebreath Framework

I need to create the classes in C# and call that classes from javascript through C++CLI and Firebreath Framework .. create the complex hierarchy class structure and expose it from javacsript
The flow should be :
Javascript <-- C++(FireBreath)<-- C#
C#-->C++(Firebreath)-->Javascript
I have to create the generalized solution for this problem.
Then how should i implement this? If you have any solution,sort of information ,ways to solve this problem then please let me know..
Suppose my Class Library in C# which includes the classes like :
public class TestImage
{
}
public class DrawImage
{
public void ShowImage(TestImage testImage)
{
}
}
Here I need to call ShowImage(TestImage testImage) method from JavaScript page of Firebreath Framewaork.
I already created the wrapper but I dont have an idea to expose the class object as argument to the method like the above ShowImage () in tjhe JavaScript page of the Fireabreath Framework.
If you have any idea related to this please let me know.
When you say "generalized solution"... do you mean a tool or process that automates this?
I believe this is possible. Here's how I would do it:
I'm assuming you have gotten started with FireBreath and have some understanding of it. I'm glossing over countless problems you'll run into integrating all this within a FireBreath solution; that would take days! So this is just architectural advice. I'm sorry to omit so many details.
I would write a tool that dynamically loads your .NET assembly or assemblies, and uses reflection to traverse the 'complex hierarchy class structure'. This tool would generate two things: A C++/CLI wrapper for your .NET library, and a set of native C++ FireBreath classes that bind from Javascript to that C++/CLI wrapper.
The C++/CLI wrapper (see enter link description here) makes your .NET library callable from the native C++ of FireBreath.
Actually, here is a tool on CodePlex that claims to generate such a wrapper.
The Javascript adapter is a set of .cpp modules (probably one for each of your library/C++/CLI classes). Each of these is a C++ class derived from FB::JSAPIAuto, which allows these classes to be instantiated as Javascript objects. Within the constructor for each of these classes, the automated tool inserts code to create the object's Javascript API. Code that looks like this:
registerMethod("Start", make_method(this, &thisClass::Start));
registerMethod("Abort", make_method(this, &thisClass::Abort));
registerProperty("Size", make_property(this, &thisClass::get_Size,&thisClass::set_Size));
The automated tool must synthesize these methods of the class, like thisClass::Start and thisClass::set_Size. Their parameters and return types are the Javascript-compatible types supported by FireBreath - like int and double and bool, but also std::string, FB::VariantMap and FB::VariantList. In the body of each such method, the tool generates code to call the corresponding C++/CLI wrapper API, doing any necessary conversion between parameters and returns.
I suppose that each FB::JSAPIAuto-derived class inherits from, has as a member, or holds a pointer to, the C++/CLI class/object it represents.
As a FireBreath project, your .NET library is ultimately represented by a GUID - this is how Javascript finds its way into your library, by creating a root object from that GUID. It then calls methods or reads properties of that object to get other objects, and so on to access your entire library API.
I suppose there will be some issues mapping between Javascript and C#. You will have to study the Javascript parameter and return types supported by FireBreath, and limit your C# API accordingly. Probably key is figuring out how Javascript objects and arrays are represented as they cross the C++/CLI layer.
I've just achieved something like this using COM. I exposed the C# library as a COM object, then wrote a couple of wrapper functions which called this library in FireBreath. (I was lucky thought I had a very simple API).

Properly exposing functions in VB class library using c#

I have to communicate with a controller that uses an unmanaged DLL in C#. The documentation isn't very helpful for the DLL and I have no experience with talking to DLL's. The company does provide a sample VB project with a class that wraps the DLL from VB. The class is called ctccom32v2.
I thought that since the dirty work of calling the unmanaged DLL is already done including structs and other variables, I could use that class to create a VB class library. I figure it will save me a lot of time and effort. So I added that class source file to a VB class library project and it spat out a dll when built. I then added that dll to my C# project references and I am able to see the functions in the reference browser. The library I created is named CTC_Lib.
(if your wondering why I just don't write my program in VB and use their class, I prefer and I am more comfortable working in C#)
The problem I am running into is this:
If I create an instance of the library using
CTC_Lib.Ctccom32v2 ctc = new CTC_Lib.Ctccom32v2();
and then attempt to type ctc.somefunction, intellisense shows a few default methods like Equals, GetHashCode, etc. I do not see any of the Ctccom32v2 functions which expose the unmanaged DLL.
if I type the library and class name manually like so:
CTC_Lib.Ctccom32v2.
The intellisense list pops up with all of the functions in Ctccom32v2.
If I add another class to the VB class library (Lets call it "somelib") and stick a simple function into it:
Public Function add() as Void
Return 1+2;
End Function
I then use the same method for creating an instance:
CTC_Lib.somelib ctc = new CTC_Lib.somelib();
the function "add" now pops up in the intellisense window by simply typing ctc.
Could it because the way the functions are declared in the VB class? Here is one of MANY functions in the VB class, they are all declared the same using "Declare Auto Function":
Declare Auto Function CtOpenConnection Lib "Ctccom32v2.dll" _
(ByVal ConnectID As Integer, ByVal CommPort As Integer, ByVal Address As Integer) As Integer
I don't know what Auto function means but that does not expose the function when you attempt to create an instance of the class it resides in.
If this is or is not the proper way to call those functions within the VB class library please let me know, I am a novice. Also, forgive me if some of my terminology is incorrect; I am not good with programming jargon (yet).
The intellisense differs in your two scenarios because the unmanaged DLL lacks the required metadata to properly display the information about the functions. Your VB function does possess that metadata.
You already know the workaround; type the library and class name manually. Alternatively, you can wrap the unmanaged functions in managed VB methods, which will provide the needed metadata for intellisensing.
See the MSDN documentation on the Declare statement. This looks similar to declaring an extern method in C#. I think what you're missing is the access modifier. It should be like Public Declare ... to allow it to be used outside of where it's declared.
If that wasn't the issue, you might want to declare it as a Public Shared Function in a public class, using DllImport. An example of that is shown at the bottom of the Declare statement doc.
It can also be useful, maybe for this, and for C#/VB conversions in general, to decompile your assembly in ILSpy and see what is generated due to these lines.

Optional Interface in Class Libraries

I have an interface called IProjectUser that defines a read function and a write function for reading and writing to project files. I also have a class called Project that holds a generic list of IProjectUser objects to manage project files. Both of these are in the class library Project.dll.
I also have a class library called A.dll that contains a class called Foo which implements IProjectUser. The ability to read/write project files is secondary to this class. It holds and manipulates some data. A.dll references Project.dll.
The application also contains some forms and other classes that implement IProjectUser.
I can imagine a situation in the future where I might want to use A.dll in another project that doesn't use project files. However I will be forced to include Project.dll just because A.dll requires it. Even though the functionality is optional.
Is there a different design pattern that would allow me to essentially make an interface optional?
I hope I explained this clearly enough.
Update
What about casting objects to interfaces? This would open up the possibility that an interface is not implemented correctly. Is that a good or bad design approach for this kind of problem?
if (Foo is IProjectUser) {
ProjectUsers.Add(Foo as IProjectUser);
// etc
}
Use inherited or multiple interfaces. You cannot make an interface method optional.
Casting your object to an interface that it doesn't implement will not work -- you'll end up with a null value in your variable. What's wrong with using proper design and adding B.dll as suggested below? A.dll becomes completely reusable, and you still get to have a version of Foo that implements IProjectUser.
Drop the reference to Project.dll from A.dll.
Drop IProjectUser from Foo.
Create B.dll which references Project.dll and A.dll.
Create FooProjectUser in B.dll which inherits from Foo and implements IProjectUser.
Move the project specific logic from Foo into FooProjectUser.
Use FooProjectUser in the places where you currently use Foo, freeing A.dll from any references to Project.dll.

Using a C++ dll in C#

I'm attempting to consume a dll written in C++ from a C# application. I have 3rd party source code for the C++ dll (the Cyclone physics engine) and do not want to manually port it over to C#.
In the C++ project
I changed it to output a dll. I changed it to use the /clr flag. I changed it to use Multi-threaded Debug DLL (/MDd) because that was the only one compatible with /clr and also compiled.
In the C# project
I added a reference to the dll. I'm using the cyclone namespace.
At first there was absolutely nothing under the namespace. I think this is because in the C++ code, all classes were declared with no access modifiers and the default is private. So for the class "Particle" I changed the definition to:
public class Particle
{
//...
}
Now I can successfully declare a variable of type Particle from the C# code. However, intellesense and the object browser report Particle to be a struct (?) and it doesn't contain any methods at all. The c++ code declares a bunch of methods after "public:" access modifiers so I don't know what the problem is.
For example,
public:
void integrate(real duration);
What am I doing wrong?
The Particle class is not a managed class, hence it is treated as a struct. You need to use the ref keyword to make it managed and garbage collected. You also need to do the same to every other class that references it which might be a problem. The best solution I think, is to create a managed wrapper class that uses the Particle class internally. This wrapper class can then be referenced by .net.
See here:
I have not actually run into your exact problem before, but I have used C++ dlls in c# before. Typically when calling a dll like that you would use the dllImport keyword. Basically you can define a class that imports all the types and methods from the c++ dll. You can then call those wrapper classes.
I am far from an expert on it, but I have used it to get access to win32 methods and some other libraries that I needed to use.
This link on codeplex has a few links tools that might help. But the most important is probably the Interop Assistant. It can generate the C# wrappers for your c++ dll.
This isn't exactly what you are asking, but I thought it might help to look at a different direction.
Try declaring the c++ class with the ref keyword:
public ref class Particle
Do you have a reference to COM Interop?

Categories

Resources