473,659 Members | 3,553 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory Allication (Managed VC++ DLL to Unmanaged DLL) [Second Try]

(Sorry for spamming multiple groups, But I need a solution to this problem)

I think this should be a simple question on Memory Allocation in a managed DLL and passing a memory pointer over to an unmanaged DLL.

I have a "Unmanaged" Client DLL that I'm creating a Managed "wrapper" to be used in VB.Net and/or C#..

In the my Client DLL (unmanaged), There are several functions where I need to allocate a "client side" memory buffer to marshall data into from the server side of the application.

Normally in VC++ 7.1 (unmanaged) I would normally just malloc the memory that I needed:

UBYTE *pDataPtr = NULL;
DWORD dwDataSize = 0;

try
{
GetServerSideDa taSize(dwDataSi ze);
pDataPtr = (UBYTE *)malloc(dwData Size);
if (pDataPtr)
{
GetServerSideDa ta(pDataPtr);
// Do something with pData Now..
free(pDataPtr);
pDataPtr = NULL;
}
}
catch(...)
{
if (pDataPtr)
free(pDataPtr);
}

In my Managed DLL wrapper I've done this so far which fails when I call "new" on the VB.Net side..

namespace CDMSClient_SQL
{
[DllImport("CDMS Client.dll", EntryPoint = "SQLGetRows ", CharSet = Ansi)]
STATUS SQLGetRows(cons t Int32 RowCount, const Int32 DataSize, UBYTE *Data, String *Columns, String *From, String *Where, String *OrderBy);

[DllImport("CDMS Client.dll", EntryPoint = "SQLGetRowInfo" , CharSet = Ansi)]
STATUS SQLGetRowInfo(I nt32 &RowCount, Int32 &ColumnCount , Int32 &DataSize, String *Columns, String *From, String *Where);
}
Array *CCDMSClientInt erface::SQLGetR ows(const Int32 MaxRows, String *Columns, String *From, String *Where, String *OrderBy)
{
STATUS Status = EC_OK;
Int32 dwRowCount = 0;
Int32 dwColumnCount = 0;
Int32 dwDataSize = 0;
Array *Data = NULL;
UBYTE __pin *pDataPtr = NULL;

Status = CDMSClient_SQL: :SQLGetRowInfo( dwRowCount, dwColumnCount, dwDataSize, Columns, From, Where);
if (Status == EC_OK)
{
pDataPtr = (UBYTE *)new char[dwDataSize]; // <--- This is the line that fails in the Managed VC++ Side
Status = CDMSClient_SQL: :SQLGetRows(dwR owCount, dwDataSize, pDataPtr, "*", "CDMS_Confi g", "", "");
if (Status == EC_OK)
Data = Convert_CDBArra y_2_Object(pDat aPtr);
}

return (Data);
}

VB.Net Side of code:

Imports ClientInterface = CDMSClientDotNe t.CCDMSClientIn terface

Module Module1

Sub Main()
Dim ci As ClientInterface = New ClientInterface
Dim Data As Array
Dim Status As Int32

Status = ci.SetApplicati onID("43C1F2F1-CB68-4B89-A8C8-5E0C42CE4866")
If Status = 1 Then
Status = ci.SetDomain("P rimary")
If Status = 1 Then
Status = ci.CreateServer Context()
If Status = 1 Then
Status = ci.Login("admin ", "optical")
If Status = 1 Then
Console.WriteLi ne("Logged In!")

Data = ci.SQLGetRows(1 000, "*", "CDMS_Confi g", "", "") // <---This is the line that fails in the VB.Net side

ci.Logout()
Else
Console.WriteLi ne("Failed to Login!")
End If
ci.DeleteServer Context()
Else
Console.WriteLi ne("Failed to Create Server Context!")
End If
Else
Console.WriteLi ne("Failed to Set Domain!")
End If
Else
Console.WriteLi ne("Failed to Set ApplicationID!" )
End If
End Sub

End Module
I have many functions that pass data from the server side to the client side via a memory buffer. This data in the memory buffer is parsed and put back into a dynamic array (Custom C++ class called a CDBArray). The first function that I'm trying to get to work, fetches a database table from the server side and marshalls it back over to the client side. The Server and Client is using RPC to marshall data back and forth. (Just a side note, The client side can not access the database directly via ODBC or anything else. It must go thought my client dll. This is done for security reason to keep the client side locked down.)

Any ideas or suggestion are more than welcomed!!

Thanks Again!
Weston Fryatt

Jul 21 '05 #1
2 2289
Weston Fryatt" <wfryatt "at wrote:
In my Managed DLL wrapper I've done this so far which fails when I
call "new" on the VB.Net side.. namespace CDMSClient_SQL
{
[DllImport("CDMS Client.dll", EntryPoint = "SQLGetRows ", CharSet =
Ansi)]
STATUS SQLGetRows(cons t Int32 RowCount, const Int32 DataSize,
UBYTE *Data, String *Columns, String *From, String *Where, String
*OrderBy);

[DllImport("CDMS Client.dll", EntryPoint = "SQLGetRowInfo" ,
CharSet = Ansi)]
STATUS SQLGetRowInfo(I nt32 &RowCount, Int32 &ColumnCount ,
Int32 &DataSize, String *Columns, String *From, String *Where);
}
This is managed C++? If so, why are you using platform invoke to access the
methods. Why don't you use an import library (.lib) and use IJW?
Array *CCDMSClientInt erface::SQLGetR ows(const Int32 MaxRows, String
*Columns, String *From, String *Where, String *OrderBy)
Note that const means nothing to .NET and since you are calling this class
with VB.NET the constness of MaxRows is ignored. What is Array? Is this
System::Array? If so, why are you returning an untyped array?
pDataPtr = (UBYTE *)new char[dwDataSize]; // <--- This is
the line that fails in the Managed VC++ Side
Since you are using unmanaged pointers this should call the unmanaged new.
To make absolutely sure you can write it as

pDataPtr = (UBYTE *)__nogc new char[dwDataSize];

are you sure that this is where the error lies? What is the error message?
have you tried testing dwDataSize to see if it is not zero, and pDataPtr to
see if it is not null?
Status = CDMSClient_SQL: :SQLGetRows(dwR owCount, dwDataSize,
pDataPtr, "*", "CDMS_Confi g", "", "");
if (Status == EC_OK)
Data = Convert_CDBArra y_2_Object(pDat aPtr);
}
Where do you call delete []?

If SQLGetRows does not care where the memory comes from you can use
Marshal::AllocH Global or Marshal::AllocC oTaskMem and then use the
appropriate FreeCoTaskMem and FreeHGlobal. Both of these returns a IntPtr
which can be cast to a void* and then assigned to a pinning pointer.
However, the C++ new should work fine as long as you call delete []
somewhere. (Personally I would bracket the code in try/__finally and call
delete [] in the __finally clause.)

Imports ClientInterface = CDMSClientDotNe t.CCDMSClientIn terface
This is poor naming, it's a class, not an interface, you cannot call New on
an interface!
Module Module1

Dim Data As Array

Data = ci.SQLGetRows(1 000, "*",
"CDMS_Confi g", "", "") // <---This is the line that fails in the VB.Net
side
Again System.Array is not much use. You should write the managed C++ to
return a typed array instead.
I have many functions that pass data from the server side to the
client side via a memory buffer. This data in the memory buffer is
parsed and put back into a dynamic array (Custom C++ class called a
CDBArray). The first function that I'm trying to get to work,
fetches a database table from the server side and marshalls it back
over to the client side. The Server and Client is using RPC to
marshall data back and forth. (Just a side note, The client side can


RPC should handle any type of memory you pass to it, the RPC layer will
allocate the appropriate buffer. The only time that you'll get a problem is
if you're returning a new array from the RPC method. Are any of the pointers
in SQLGetRows [in,out]?

Richard
--
www.richardgrimes.com
my email ev******@zicf.b et is encrypted with ROT13 (www.rot13.org)
Jul 21 '05 #2
Thanks Richard!

Marshal::AllocH Global() did the trick!


"Richard Grimes [MVP]" <read my sig> wrote in message
news:uJ******** ******@TK2MSFTN GP10.phx.gbl...
Weston Fryatt" <wfryatt "at wrote:
In my Managed DLL wrapper I've done this so far which fails when I
call "new" on the VB.Net side..
namespace CDMSClient_SQL
{
[DllImport("CDMS Client.dll", EntryPoint = "SQLGetRows ", CharSet =
Ansi)]
STATUS SQLGetRows(cons t Int32 RowCount, const Int32 DataSize,
UBYTE *Data, String *Columns, String *From, String *Where, String
*OrderBy);

[DllImport("CDMS Client.dll", EntryPoint = "SQLGetRowInfo" ,
CharSet = Ansi)]
STATUS SQLGetRowInfo(I nt32 &RowCount, Int32 &ColumnCount ,
Int32 &DataSize, String *Columns, String *From, String *Where);
}


This is managed C++? If so, why are you using platform invoke to access

the methods. Why don't you use an import library (.lib) and use IJW?
Array *CCDMSClientInt erface::SQLGetR ows(const Int32 MaxRows, String
*Columns, String *From, String *Where, String *OrderBy)
Note that const means nothing to .NET and since you are calling this class
with VB.NET the constness of MaxRows is ignored. What is Array? Is this
System::Array? If so, why are you returning an untyped array?
pDataPtr = (UBYTE *)new char[dwDataSize]; // <--- This is
the line that fails in the Managed VC++ Side


Since you are using unmanaged pointers this should call the unmanaged new.
To make absolutely sure you can write it as

pDataPtr = (UBYTE *)__nogc new char[dwDataSize];

are you sure that this is where the error lies? What is the error message?
have you tried testing dwDataSize to see if it is not zero, and pDataPtr

to see if it is not null?
Status = CDMSClient_SQL: :SQLGetRows(dwR owCount, dwDataSize,
pDataPtr, "*", "CDMS_Confi g", "", "");
if (Status == EC_OK)
Data = Convert_CDBArra y_2_Object(pDat aPtr);
}
Where do you call delete []?

If SQLGetRows does not care where the memory comes from you can use
Marshal::AllocH Global or Marshal::AllocC oTaskMem and then use the
appropriate FreeCoTaskMem and FreeHGlobal. Both of these returns a IntPtr
which can be cast to a void* and then assigned to a pinning pointer.
However, the C++ new should work fine as long as you call delete []
somewhere. (Personally I would bracket the code in try/__finally and call
delete [] in the __finally clause.)

Imports ClientInterface = CDMSClientDotNe t.CCDMSClientIn terface


This is poor naming, it's a class, not an interface, you cannot call New

on an interface!
Module Module1

Dim Data As Array

Data = ci.SQLGetRows(1 000, "*",
"CDMS_Confi g", "", "") // <---This is the line that fails in the VB.Net
side
Again System.Array is not much use. You should write the managed C++ to
return a typed array instead.
I have many functions that pass data from the server side to the
client side via a memory buffer. This data in the memory buffer is
parsed and put back into a dynamic array (Custom C++ class called a
CDBArray). The first function that I'm trying to get to work,
fetches a database table from the server side and marshalls it back
over to the client side. The Server and Client is using RPC to
marshall data back and forth. (Just a side note, The client side can


RPC should handle any type of memory you pass to it, the RPC layer will
allocate the appropriate buffer. The only time that you'll get a problem

is if you're returning a new array from the RPC method. Are any of the pointers in SQLGetRows [in,out]?

Richard
--
www.richardgrimes.com
my email ev******@zicf.b et is encrypted with ROT13 (www.rot13.org)

Jul 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3271
by: Tom | last post by:
We have a VERY simple .NET C# Form Application, that has about a 23MB Memory Footprint. It starts a window runs a process and does a regular expression. I have done a GC.Collect to make sure that, no memory is lying around. GC reports only 84k of allocations. Starting 5-10 of this apps is going to start taking a considerable amount of memory. Is there a way to reduce this? Tom
20
4215
by: Philip Carnstam | last post by:
How come .Net applications use so much memory? Every application I compile uses at least 10 MB of memory, even the ones consisting of only a form and nothing else. If I minimize them though the memory usage drops to a couple hundred KB. Why? Is there anything I should to to prevent this? I have compiled in release and deactivated all forms of debugging, I think! Thanks, Philip
0
3899
by: Frank Lopez | last post by:
Does anyone know if Microsoft generated a whitepaper on this topic? Does anyone know what the solution is? (meaning, eliminate the leak problem -- I am seeing three memory leaks from dllmodul.cpp(102) similar to what is mentioned below)... I am calling MFC as part of unmanaged code used by the managed code. +--------
4
7173
by: repstat | last post by:
Hi I have a project which is going to be doing some string manipulation which needs to be pretty fast. The user interface is going to be written in C#. I am going to write the string handling functions in a C++ DLL. My first question is, if I insert a C++ project into my C# solution, how will VS.NET know that I want it to be unmanaged code? I intend to be calling the DLLs functions using DllImport. I've heard that you can have unmanaged...
4
2164
by: | last post by:
I am stuck in a situation and I do believe that this should work, but it doesn't. I have a unmanaged dll, that uses MFC. This works great. Now I recompile the unmanaged dll so it contains mixed mode managed/unmanaged code, but only use unmanaged code, but this gives a error the moment I want to display a MFC dialog box: Something like unreferenced object,... during runtime.
2
219
by: Weston Fryatt | last post by:
(Sorry for spamming multiple groups, But I need a solution to this problem) I think this should be a simple question on Memory Allocation in a managed DLL and passing a memory pointer over to an unmanaged DLL. I have a "Unmanaged" Client DLL that I'm creating a Managed "wrapper" to be used in VB.Net and/or C#.. In the my Client DLL (unmanaged), There are several functions where I need to allocate a "client side" memory buffer to...
0
1605
by: Maxwell | last post by:
Hello, I recently completed a MC++ (VS2003) DLL that wraps a non MFC C++ DLL and need to use it in a MC++ Console Application (no forms/guis of any kind just output to console). Trouble is that when I ran it and looked at memory usage (in Windows task manager) it looked as if there was a very slow leak. To isolate the issue:
9
3117
by: Amit Dedhia | last post by:
Hi All I have a VC++ 2005 MFC application with all classes defined as unmanaged classes. I want to write my application data in xml format. Since ADO.NET has buit in functions available for this, I want to use it. Is it possible to call Managed class functions from Unmanaged class? How to do it? I did something like this. I declared a managed class (in C++ CLI) called as MyManagedClass whose
3
4702
by: Klaus | last post by:
Hi, I have an existing VC 6 MFC application which communicates asynchronly with a VC 2005 managed code dll. I use an unmanaged base class with virtual functions to access methods in the MFC application. Furthermore, I use a pointer to an unmanaged function to jump back into the managed dll. The managed part is basically a remoting enhancement which asynchronly
0
8337
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,...
0
8748
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8531
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
7359
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...
0
5650
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
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2754
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
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.